I want to create a body with a different part, and if I know the part's name, I can create the corresponding instance with a factory.Just as below:
template<typename Part>
class Body
{};
class Part1
{};
class Part2
{};
enum class E
{
part1,
part2,
};
template<E e>
class Factory
{
public:
static unique_ptr<Body<>> create()
{
if (e == E::part1)
{
return make_unique<Body<Part1>>();
}
else
{
return make_unique<Body<Part2>>();
}
}
};
int main()
{
auto f=Factory<E::part1>();
return 0;
}
Certainly it fails at compile time,so how could I get my porpuse?
CodePudding user response:
There's nothing here with a non-type template argument, so your title is confusing.
I assume your compiler error is complaining about
Body<>
Well, that's an error. Body is not a type, but a template. It needs an argument and there is no default.
The code wants it to be a Body<Part1>
or a Body<Part2>
but there is no such thing as a "Body of anything" as you implied.
You can have a type that holds either type by using a variant
. For example,
using BodyPart = std::variant<Body<Part1>,Body<Part2>>;
But you'll have to learn how to use that value effectively (best with visitors), as it's not the same as a polymorphic type nor a generic (compile time) template.