我正在尝试编写一个分别处理数字和非数字数据的流类。有人可以向我解释为什么这段代码无法编译吗?
#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,而且你也错误地使用了特征(没有 ::value
, is_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/