我正在尝试实现 has_equal_operator
在 C++11 中,到目前为止提出了以下解决方案。它适用于像 int
这样的简单情况或 struct A{}
但对于 std::vector<A>
失败(返回误报) .为什么会失败以及如何解决这个问题?
#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;
}
输出:
has_equal_operator<int>: 1
has_equal_operator<A>: 0
has_equal_operator<std::vector<A>>: 1
最佳答案
Why does it failing?
std::vector<A>
有一个非成员(member) operator==
函数模板,匹配 ==
在 std::declval<T>() == std::declval<T>()
在你的代码中。所以检查成功。
该函数模板的主体无法编译这一事实与 SFINAE 无关;重要的是声明有效。
How to fix this?
我能想到的唯一方法是手动将您的特征专门化为标准容器。
关于c++ - has_equal_operator 在 C++11 中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37177592/