I have some objects like this:
Obj o1{};
Obj o2{};
Obj o3{};
...
However, I also have another class Foo
which has a std::vector<Obj*>
as a member.
How can I initialise the vector
from an arbitrary list?
I would like to construct Foo like this:
Foo f{o1, o3, o4};
I have tried this knowing that I can't have collections of references.
class Foo {
public:
explicit Foo(std::initializer_list<Obj&> px) {
for (auto& p : px) {
fwds.push_back(&p);
}
}
...
private:
std::vector<Obj*> fwds;
};
The error I get in this case is:
... include\initializer_list(25,1): error C2528: 'abstract declarator': pointer to reference is illegal
With std::reference_wrapper
, you might do:
explicit Foo(std::initializer_list<std::reference_wrapper<Obj>> px) {
for (auto& p : px) {
fwds.push_back(&p.get());
}
}
Demo
Note: You might also want to promote your members to std::vector<std::reference_wrapper<Obj>> fwds;
, which simplify the constructor too.
You could do it this way:
class Foo {
public:
template <typename... Objs,
std::enable_if_t<(std::is_base_of_v<Obj, Objs> && ...), int> = 0>
explicit Foo(Objs&... o)
: fwds{&o...}
{ }
private:
std::vector<Obj*> fwds;
};
which in C++20 becomes:
class Foo {
public:
explicit Foo(std::derived_from<Obj> auto&... o)
: fwds{&o...}
{ }
private:
std::vector<Obj*> fwds;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With