c++ - 基本类型的模板特化

标签 c++ templates metaprogramming generic-programming

有什么方法可以只为基本类型制作模板特化吗? 我已尝试执行以下操作:

template<typename T, typename = typename std::enable_if<!std::is_fundamental<T>::value>::type>
class foo
{
}

template<typename T, typename = typename std::enable_if<std::is_fundamental<T>::value>::type>
class foo
{
}

但是我得到一个模板已经定义的错误。

最佳答案

这里您创建了两个同名的模板类,而不是特化类。

您需要创建一个通用的然后专门化它:

// not specialized template (for non-fundamental types), Enabler will 
// be used to specialize for fundamental types
template <class T, class Enabler = void>
class foo { };

// specialization for fundamental types
template <class T>
class foo<T, std::enable_if_t<std::is_fundamental<T>::value>> { };

关于c++ - 基本类型的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45244809/

相关文章:

c++ - 模板类的多个模板模板参数

c++ - 内存堆损坏 + GFlags 工具但不是结果

c++ - 查找具有给定 GCD 值的数字

c++ - 类引用授予对私有(private)成员的访问权限

c++ - 函数模板参数推导是否应该考虑转换运算符?

css - 如何更改 CSS 模板中的列顺序以将重要内容放在前面?

c++ - 编译错误:使用 constexpr 声明 std::array 大小

c++ - 元组处理中的模板函数错误

c++ - begin() 和 end() 函数不应该是模板类 Vector 的成员函数吗?

c++ - 在派生类型中使用可分配的目标变量