[英]has_equal_operator implementation in C++11
I am trying to implement has_equal_operator
in C++11 and so far came up with following solution. 我试图在C ++ 11中实现
has_equal_operator
,到目前为止提出了以下解决方案。 It works for simple cases like int
or struct A{}
but fails (returning false positive) for std::vector<A>
. 它适用于简单的情况,如
int
或struct A{}
但对于std::vector<A>
失败(返回误报)。 Why is it failing and how to fix this? 为什么失败以及如何解决这个问题?
#include <vector>
#include <iostream>
template<typename T>
constexpr auto has_equal_operator(int) -> decltype(std::declval<T>() == std::declval<T>(), bool()) { return true; }
template<typename T>
constexpr bool has_equal_operator(...) { return false; }
struct A {};
void test()
{
std::cout << "has_equal_operator<int>: " << has_equal_operator<int>(0) << std::endl;
std::cout << "has_equal_operator<A>: " << has_equal_operator< A >(0) << std::endl;
std::cout << "has_equal_operator<std::vector<A>>: " << has_equal_operator< std::vector<A> >(0) << std::endl;
}
Output: 输出:
has_equal_operator<int>: 1
has_equal_operator<A>: 0
has_equal_operator<std::vector<A>>: 1
Why does it failing?
它为什么失败?
std::vector<A>
has a non-member operator==
function template, which is a match for the ==
in std::declval<T>() == std::declval<T>()
in your code. std::vector<A>
有一个非成员operator==
函数模板,它与代码中的==
in std::declval<T>() == std::declval<T>()
。 So the check succeeds. 所以检查成功了。
The fact that the body of that function template won't compile is irrelevant to SFINAE; 该功能模板的主体不能编译的事实与SFINAE无关; all that matters is that the declaration is valid.
重要的是声明是有效的。
How to fix this?
如何解决这个问题?
The only way I can think of is to manually specialize your trait for standard containers. 我能想到的唯一方法是手动专门化标准容器的特性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.