C++11中的has_equal_operator实现

9

我正在尝试在C++11中实现has_equal_operator,目前想出了以下解决方案。它适用于简单的情况,如intstruct 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

2
你是说这是误报吗?== 对于两个向量不起作用吗? - user253751
1
@immibis 如果元素类型没有定义 operator ==,则不应该定义 std::vectoroperator == - o11c
1
我认为这可能与bool operator==(const vector<_Tp, _Allocator>& __x, const vector<_Tp, _Allocator>& __y)不依赖于declval<_Tp>() == declval<_Tp>()的有效性有关。 - o11c
@immibis,has_equal_operator<std::vector<A>>返回true,但实际上应该是false。正如o11c指出的那样,A() == A()未定义。 - Yatima
3
这是EWG问题47,但我不太理解为什么会被否定建议(NAD'd)。 - T.C.
网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接