0

I would like to do something similar to this:

#include <list>
#include <iostream>
#include <functional>

class Abstract {
public:
  virtual void foo() = 0;
};

class Concrete : public Abstract {
  void foo() {
    std::cout << "foo's implementation" << std::endl;
  }
};

typedef std::list<Abstract> abstract_list;

class Someclass {
public:
  Someclass(abstract_list list) : m_list(list) {}
private:
  abstract_list m_list;
};

int main(int argc, char **argv) {
  Someclass l({ Concrete(), Concrete() });
  return 0;
}

Now, I know I can't. Abstract being incomplete, it cannot be used as is in the container. I don't want to use pointers (raw ppointer or unique_ptr).

I try to rewrite my type as:

typedef std::list<std::reference_wrapper<Abstract> > abstract_list;

But it fails with

error: use of deleted function ‘std::reference_wrapper<_Tp>::reference_wrapper(_Tp&&) [with _Tp = Abstract]’

Because std::reference_wrapper do not work with rvalue.

Is there any other option to statically allocate a list containing abstract entities using an elegant braced initializer list ?

Luke Skywalker
  • 1,464
  • 3
  • 17
  • 35
  • You misunderstand what a reference wrapper does. It wraps a reference. In order to do that, the reference needs to refer to something that exists. You attempt to refer to a temporary object, which doesn't make sense. I think your entire approach doesn't make sense; it looks like you really want a `std::list>` so that the list *owns* its contained elements. – Kerrek SB Jul 18 '15 at 11:50
  • My problem is unique_ptr can be NULL. That is why I don't want pointers, I don't want to keep checking for NULLity. With move semantics, there should be a way to move the object you just created locally into the list. – Luke Skywalker Jul 18 '15 at 11:54
  • The StdLib containers *contain elements of one specific type*. Therefore, either you wrap `Abstract` in some kind of RAII-type-erased wrapper (e.g. a wrapper class for `unique_ptr` with the class invariant that the pointer is never null), or you look for container classes outside the C++ Standard Library. – dyp Jul 18 '15 at 12:07
  • I've not tried it, but you might be interested in [nn: Non-nullable pointers for C++](https://github.com/dropbox/nn) – Chris Drew Jul 18 '15 at 12:20
  • It looks like you're after some kind of "smart reference", which is what the proponents of `operator.` claim is useful. For now, as long as we don't have that, I recommend you ensure the non-nullness of the pointers by appropriate API design rather than ad-hoc checks. – Kerrek SB Jul 18 '15 at 17:46

0 Answers0