“在类模板专门化中期望'>'”?

问题描述 投票:2回答:1

我正在编写一个只希望与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> {
    //...
};

编译器告诉我'='是语法错误,因为它在期待'>',这没有多大意义。我觉得我还没有完全掌握部分模板的专业知识,我还缺少什么?

c++ templates template-specialization
1个回答
3
投票

在专业化中,紧随类名的模板参数列表必须仅包含类型和值。

您不能在其中放置默认参数,它们属于主模板。而且您在那里不需要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>);以防止意外使用。

© www.soinside.com 2019 - 2024. All rights reserved.