I have an attribute vector that can hold different types:
class base_attribute_vector; // no template args
template
class raw_attribute_ve
enum class Type
{
Int,
String,
// ...
Unknown
};
Type TypeFromString(const std::string& s)
{
if (s == "int") { return Type::Int; }
if (s == "string") { return Type::String; }
// ...
return Type::Unknown;
}
template class>
struct base_of;
template class C>
using base_of_t = typename base_of::type;
And then the generic factory
template class C>
std::unique_ptr> make_templated(const std::string& typeStr)
{
Type type = TypeFromString(typeStr);
static const std::map>()>> factory{
{Type::Int, [] { return std::make_unique>(); } },
{Type::String, [] { return std::make_unique>(); } },
// ...
{Type::Unknown, [] { return nullptr; } }
};
return factory.at(type)();
}
a specialization is needed for each base:
template <>
struct base_of {
using type = base_attribute_vector;
};
And then
auto p = make_templated(s);
Demo