"expected a '>'" class 模板专业化?

"expected a '>'" in class template specialization?

我正在写一个 class,我希望它只与 std::is_arithmetic 模板适用的类型一起使用。我的代码如下:

#include <type_traits>

template<typename A, typename B>
class Stream {};

template <typename T>
class Stream <typename T,
    typename std::enable_if<std::is_arithmetic<T>::value>::type * = nullptr> {
    //...
};

编译器告诉我“=”是一个语法错误,因为它需要一个“>”,这没有多大意义。我觉得我还没有完全掌握部分模板专业化,我错过了什么?

在特化中,class 名称后的模板参数列表必须仅包含类型和值。

您不能将默认参数放在那里,它们属于主模板。
而且你不需要 typename 那里(除非你有一个依赖类型,例如 typename std::enable_if<...T...>)。

这是您的代码的工作版本:

template<typename A, typename = void>
class Stream {};

template <typename T>
class Stream<T, std::enable_if_t<std::is_arithmetic_v<T>>>
{};

请注意,可以通过将非 void 类型传递给第二个参数来规避检查。您可能应该在主模板中添加 static_assert(std::is_void_v<T>); 以防止意外误用。