c++ - 整数类型的模板函数特化

标签 c++ templates

假设我有一个模板函数:

template<typename T>
void f(T t)
{
    ...
}

我想为所有原始整数类型编写一个特化。执行此操作的最佳方法是什么?

我的意思是:

template<typename I where is_integral<I>::value is true>
void f(I i)
{
    ...
}

然后编译器为整数类型选择第二个版本,为其他所有类型选择第一个版本?

最佳答案

使用SFINAE

// For all types except integral types:
template<typename T>
typename std::enable_if<!std::is_integral<T>::value>::type f(T t)
{
    // ...
}

// For integral types only:
template<typename T>
typename std::enable_if<std::is_integral<T>::value>::type f(T t)
{
    // ...
}

请注意,即使是声明,您也必须包含完整的 std::enable_if 返回值。

C++17 更新:

// For all types except integral types:
template<typename T>
std::enable_if_t<!std::is_integral_v<T>> f(T t)
{
    // ...
}

// For integral types only:
template<typename T>
std::enable_if_t<std::is_integral_v<T>> f(T t)
{
    // ...
}

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

相关文章:

c++ - C++中的多重继承

c++ - 如何在 block 中途重命名变量?

c++ - 使用模板模板参数对 'operator<<' 进行模糊重载

c++ - 如何避免模版函数调用不明确?

wpf - 设置 wpf 数据网格的样式

c++ - 将 tag1 tag2 tag3 替换为 x1 x2 x3

c++ - 遍历 multimap 中的一个组我怎么知道我是在第一个还是最后一个元素中?

c++ - 通过 C++ 在 qml 中交换 QString

c++ - 使用 C++17 编译时无法从基类访问成员类型

c++ - 如何使策略决定成员变量类型?