SFINAE 和 std::numeric_limits
SFINAE and std::numeric_limits
我正在尝试编写一个流 class 来分别处理数字和非数字数据。有人可以向我解释为什么这段代码无法编译吗?
#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<<
提供了一个非类型模板参数,但您从未为其提供参数。您需要指定一个默认参数。
示例代码:
#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;
}
我正在尝试编写一个流 class 来分别处理数字和非数字数据。有人可以向我解释为什么这段代码无法编译吗?
#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<<
提供了一个非类型模板参数,但您从未为其提供参数。您需要指定一个默认参数。
示例代码:
#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;
}