SFINAE 和 std::numeric_limits [英] SFINAE and std::numeric_limits

查看:55
本文介绍了SFINAE 和 std::numeric_limits的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a stream class that handles numerical and non-numerical data separately. Can someone explain to me why this code does not compile?

#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 是错误的,而且你也错误地使用了 trait (没有 ::value, is_integer 是一个布尔值).trait 的错误是微不足道的,SFINAE 的问题是你给你的 operator<< 提供了一个非类型模板参数,但你从来没有为它提供参数.您需要指定一个默认参数.

Because you are doing SFINAE wrong, and you are also incorrectly using the trait (there is no ::value, is_integer is a boolean). The error with trait is trivial, the problem with SFINAE is that you gave a non-type template parameter to your operator<<, but you never provide an argument for it. You need to specify a default argument.

示例代码:

#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;
}

这篇关于SFINAE 和 std::numeric_limits的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆