C++ 类型特征虚拟示例 : compiler error

标签 c++ templates typetraits

我最近遇到了一些编译器错误,归结为以下虚拟示例。基本上我正在构建一个“plus2”函数模板,我希望它只适用于 intfloat .从逻辑上讲,当“is_numerical”类型特征测试通过时,程序只会加 2。然而,它在编译时挂起并出现错误 C2782/C2784/C2676,提示将 2 添加到 string

例子仅供引用,没有意义。更重要的是,编写这种逻辑的正确方法是什么?谢谢。

#include <iostream>
#include <string>
using namespace std;
template <typename T>
struct is_numerical {
    static const bool value = false;
};
template <>
struct is_numerical<float> {
    static const bool value = true;
};
template <>
struct is_numerical<int> {
    static const bool value = true;
};

template <typename T>
T plus2(T input) {
    if (is_numerical<T>::value) {
        return input + 2;
    } else { return input; }
}
int main()
{
    //char x('a'); // prints 'a'
    string x("a"); // compiler error
    cout << plus2(x) << endl;
    return 0;
}

最佳答案

问题是,当 T input 是一个 std::string 时,您仍在尝试编译 return input + 2; . 即使它在始终为 false 的 if 语句中。

在 C++17 中,if constexpr 允许条件编译代码。

template <typename T>
T plus2(T input) {
    if constexpr (is_numerical<T>::value) {
        return input + 2;
    } else { return input; }
}

在 C++ 的所有标准版本中,SFINAE还可以防止无效代码被编译。

template <typename T>
T plus2(T input, typename std::enable_if<! is_numerical<T>::value>::type* = 0) {
    return input;
}

template <typename T>
T plus2(T input, typename std::enable_if<is_numerical<T>::value>::type* = 0) {
    return input + 2;
}

关于C++ 类型特征虚拟示例 : compiler error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48118663/

相关文章:

c++ - CRTP + 特征类 : "no type named..."

c++ - 将数组放入另一个数组

c++ - std::bit_cast 生成多个值的值表示的示例是什么?

c++ - 编译/调试 LZMA

c++ - 在同一类中使用 constexpr 作为模板参数时出错

javascript - 是否有类似 XSLT 的 JavaScript 模板系统?

c++ - 模板静态函数模板类类型推导

c++ - static_assert 内部/外部类定义

不完整类型的 C++ 导出模板实现

c# - "Promote"泛型类型在 C# 中为 Nullable?