简体   繁体   中英

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?

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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM