简体   繁体   English

在模板类型之间转换?

[英]Convert between template types?

I have a class template我有一个 class 模板

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

Foo(T&){};

};

Unfortunately, this fails when T is void .不幸的是,当Tvoid时,这会失败。 std::nullptr_t would serve the exact same purpose here, and I would much prefer that to be T . std::nullptr_t在这里可以达到完全相同的目的,我更希望它是T

Is there a way to designate that all Foo<void> should be Foo<std::nullptr_t> instead?有没有办法指定所有Foo<void>应该是Foo<std::nullptr_t>

If you want Foo<void> to actually be identical to Foo<std::nullptr_t> , you need to make Foo an alias template:如果您希望Foo<void>实际上与Foo<std::nullptr_t>相同,则需要将Foo设为别名模板:

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> .如果您不想使用别名,您仍然可以使Foo<void>具有与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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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