有条件地提供使用声明

Conditionally provide a using declaration

假设我有一个带有模板参数 T 的 class foo 并且我想为对应于 [=12 的引用和常量引用类型提供一个 using 声明=]:

template<typename T>
struct foo
{
    using reference = T&;
    using const_reference = T const&;
};

有没有一种方法可以仅在 T 不是 void 的情况下使用 declerations 来“启用”这些,而不专门化整个 class foo?

您可以从基础 class 继承 void:

template<typename T>
struct typedefs {
    using reference = T&;
    using const_reference = T const&;
};

template<>
struct typedefs<void> {};

template<typename T>
struct foo : typedefs<T>
{};

如果您不想让您的程序使用 foo<void> 编译并且不介意难看的 SFINAE,那么这是一个没有专门化的难看解决方案:

template< typename T, typename = std::enable_if_t<!std::is_same_v<void, T>>>
struct foo
{
    using reference = T&;
    using const_reference = T const&;
};