Nathan29006781
Nathan29006781

Reputation: 335

Convert between template types?

I have a class template

template <typename T=std::nullptr_t>
class Foo{

Foo(T&){};

};

Unfortunately, this fails when T is void. std::nullptr_t would serve the exact same purpose here, and I would much prefer that to be T.

Is there a way to designate that all Foo<void> should be Foo<std::nullptr_t> instead?

Upvotes: 1

Views: 55

Answers (1)

Brian Bi
Brian Bi

Reputation: 119069

If you want Foo<void> to actually be identical to Foo<std::nullptr_t>, you need to make Foo an alias template:

template <typename T>
class FooImpl {
    FooImpl(T&);
};

template <typename T=std::nullptr_t>
using Foo = FooImpl<std::conditional_t<std::is_void_v<T>, std::nullptr_t, T>>;

If you don't want to use an alias, you can still make Foo<void> have the same constructor signature as Foo<std::nullptr_t>. Nonetheless, they will be two separate types:

template <typename T=std::nullptr_t>
class Foo{
    using reference = std::conditional_t<std::is_void_v<T>, std::nullptr_t, T>&;
    Foo(reference);
};

Upvotes: 3

Related Questions