Hello,
how can pass a value to the constructor of the derived structs in this simple factory pattern? thx
Code:#include <iostream>
#include <memory>
#include <vector>
struct B {
virtual ~B() = default;
};
struct D1 : B {
int Val;
D1(int val) : Val(val) {}
};
struct D2 : B {
int Val;
D2(int val) : Val(val) {}
};
template<typename T> std::unique_ptr<B> factory(int val) {
return std::make_unique<T>(val);
}
int main() {
std::vector<std::shared_ptr<B>> vec{ factory<D1>(1), factory<D2>(2) };
for(const auto& v : vec ) std::cout << v->Val << '\n';
}