Is there a way to have a template class such as this
template<bool state = true>
class A
{
};
and have another class which can accept both A<true> and A<false> as a argument or field, without being a template class itself. Like this:
class B
{
public:
B(A& arg_a)
: a(arg_a)
{}
private:
A& a;
};
int main()
{
A<true> aTrue;
A<false> aFalse;
B bTrue(aTrue);
B bFalse(aFalse);
};
Or is this simply impossible because two objects of the same class with different template arguments are treated as different types by the compiler? Other suggestions on how to design this would also be appreciated. I know this design is possible if I just make the template parameter a class field, but I'd like to know if this can be done using templates parameters.
The two different specializations
A<true>andA<false>of the class templateAare indeed different types.You could either overload the constructors of
Bto allow each of them:or you could leverage polymorphism with any specialization of
Aderiving from a common base class:Another alternative, as mentioned by @Jarod42 in the comments, is to use
std::variant, given that you are using C++17 (or later); particularly,std::variant<A<true>, A<false>>.