c++ - SFINAE 和 std::numeric_limits

标签 c++ templates sfinae enable-if

我正在尝试编写一个分别处理数字和非数字数据的流类。有人可以向我解释为什么这段代码无法编译吗?

#include <iostream>
#include <cstdlib>

#include <type_traits>
#include <limits>

class Stream
{
public:
    Stream() {};

    template<typename T, typename std::enable_if_t<std::numeric_limits<T>::is_integer::value>>
    Stream& operator<<(const T& val)
    {
        std::cout << "I am an integer type" << std::endl;
        return *this;
    };

    template<typename T, typename std::enable_if_t<!std::numeric_limits<T>::is_integer::value>>
    Stream& operator<<(const T& val)
    {
        std::cout << "I am not an integer type" << std::endl;
        return *this;
    };
};

int main()
{
    Stream s;
    int x = 4;
    s << x;
}

最佳答案

因为你做错了 SFINAE,而且你也错误地使用了特征(没有 ::valueis_integer 是一个 bool 值)。 trait 的错误是微不足道的,SFINAE 的问题是你给了一个非类型模板参数给你的 operator<< ,但您从不为此提供论据。您需要指定一个默认参数。

示例代码:

#include <cstdlib>
#include <iostream>
#include <type_traits>
#include <limits>

class Stream
{
public:
    Stream() {};

    template<typename T, std::enable_if_t<std::numeric_limits<T>::is_integer>* = nullptr>
    Stream& operator<<(const T& val)
    {
        std::cout << "I am an integer type" << std::endl;
        return *this;
    };

    template<typename T, std::enable_if_t<!std::numeric_limits<T>::is_integer>* = nullptr>
    Stream& operator<<(const T& val)
    {
        std::cout << "I am not an integer type" << std::endl;
        return *this;
    };
};

int main()
{
    Stream s;
    int x = 4;
    s << x;
}

关于c++ - SFINAE 和 std::numeric_limits,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53124170/

相关文章:

c++ - 内部类的模板编译错误

c++ - 使用 SFINAE 的非模板类中的模板函数重载

c++ - 有了模板,如何区分两种并列的情况,比如浮点型和整数型?

c++ - 使用SFINAE计算不同元素的大小

c++ - 如何声明包含 B 类实例的结构 A,其中 B 类具有返回结构 A 的函数?

c++ - CodeBlocks 不能插入括号

c++ - 将 short*/double* 转换为 int* 并返回并取消引用

c++ - 使用标准库在 C++11 中使用 std::tie 提取嵌套在元组中的元组

c++ - 自定义类型(自己的类)的 std::rank 的实现

c++ - 可以组合部分模板特化来生成隐式生成的共享代码路径吗?