【问题标题】:SFINAE and std::numeric_limitsSFINAE 和 std::numeric_limits
【发布时间】:2018-11-02 18:40:35
【问题描述】:

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

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

【问题讨论】:

  • 您可以至少发布编译器错误(逐字)。以及相关编译器的详细信息。还有你的操作系统。请尝试提供所有可能与问题相关的信息
  • 不会真正解决问题,但std::numeric_limits&lt;T&gt;::is_integer::value 应该是std::numeric_limits&lt;T&gt;::is_integeris_integer 没有 value 成员
  • 另外,你可以使用std::is_integral

标签: c++ templates sfinae enable-if


【解决方案1】:

因为你做错了 SFINAE,而且你也错误地使用了 trait(没有::valueis_integer 是布尔值)。 trait 的错误是微不足道的,SFINAE 的问题是您为 operator&lt;&lt; 提供了一个非类型模板参数,但您从未为其提供参数。您需要指定一个默认参数。

示例代码:

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

【讨论】:

  • 啊,谢谢,所以这将第二个参数解析为 void* = nullptr 正确吗?
  • @AdamSturge 是的。
猜你喜欢
  • 2010-12-09
  • 2020-05-01
  • 2017-06-22
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2015-02-11
相关资源
最近更新 更多