I am trying to initialize a collection of pointers to class A
through an initializer list. However, the initializer list cannot use reference as a template type.
I have the following code.
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <initializer_list>
#include <memory>
struct A
{
virtual void f() const noexcept { std::cout << "A"; }
};
struct B : public A
{
virtual void f() const noexcept override { std::cout << "B"; }
};
class Test
{
std::vector<std::shared_ptr<A>> vec;
public:
Test(const std::initializer_list<A>& list)
//Test(const std::initializer_list<A&>& list) <------ Solution?
{
for (auto& x : list)
vec.push_back(std::make_shared<A>(x));
}
void print()
{
std::for_each(vec.begin(), vec.end(), [](auto x) { x->f(); });
}
};
int main()
{
Test test = { A(), B() };
test.print();
}
The code prints:
AA
It should print:
AB
Is there a simple way to do this, without having to create pointers in the calling method?
The related article (How do I implement polymorphism with std::shared_ptr?) did not provide much help with this problem.