[英]how can I handle a TMP to avoid printing whatever
I'm falling into a problem, so I want to avoid this problem which is: if I provide a class template, I have to ensure that when I enter string it returns false, it worked for primitive data type but for this class template no.我遇到了一个问题,所以我想避免这个问题:如果我提供一个 class 模板,我必须确保当我输入字符串时它返回 false,它适用于原始数据类型,但对于这个 class 模板没有.
template<class Y>
class Point
{
Y x, y;
public:
Point(){}
Point(Y _x, Y _y):x(_x),y(_y){}
~Point(){}
Point<Y>& operator++()
{
++x;
++y;
return *this;
}
};
Point<int>Pi;
template< typename, typename = void >
struct is_incrementable : std::false_type { };
template< typename T >
struct is_incrementable<T,std::void_t<decltype(++std::declval<T&>())>> : std::true_type { };
int main()
{
cout << boolalpha;
cout << is_incrementable<Point<int>>();
return 0;
}
how can I resolve that?我该如何解决?
You need to apply your is_incrementable
to operator++
to make sure you do not define that function when Y
is not incrementable.您需要将
is_incrementable
应用于operator++
以确保在Y
不可递增时不定义 function。 You can do that with SFINAE like你可以用SFINAE做到这一点
template< typename, typename = void >
struct is_incrementable : std::false_type { };
template< typename T >
struct is_incrementable<T,std::void_t<decltype(++std::declval<T&>())>> : std::true_type { };
template<class Y>
class Point
{
Y x, y;
public:
Point(){}
Point(Y _x, Y _y):x(_x),y(_y){}
~Point(){}
template <typename T = Y, std::enable_if_t<is_incrementable<T>::value, bool> = true>
// ^ ^ this is needed as SFINAE only works with the current template parameters
Point<T>& operator++()
{
++x;
++y;
return *this;
}
};
and using并使用
int main()
{
using namespace std;
cout << boolalpha;
cout << is_incrementable<Point<int>>() << "\n";
cout << is_incrementable<Point<string>>();
return 0;
}
will print将打印
true
false
which you can see in this live example你可以在这个活生生的例子中看到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.