【问题标题】:has_equal_operator implementation in C++11C++11 中的 has_equal_operator 实现
【发布时间】:2016-05-12 04:55:10
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • 什么意思,这是误报? == 不适用于您的两个向量吗?
  • @immibis std::vector's operator == 只有在为元素类型定义时才应定义。
  • 我认为这可能与bool operator==(const vector&lt;_Tp, _Allocator&gt;&amp; __x, const vector&lt;_Tp, _Allocator&gt;&amp; __y) 不依赖于declval&lt;_Tp&gt;() == declval&lt;_Tp&gt;() 的有效性有关。
  • @immibis has_equal_operator<:vector>> 返回 true,而它确实应该为 false。由于 o11c 指出 A() == A() 没有定义
  • 这是EWG issue 47,它是 NAD 的,但我不太明白其中的原理。

标签: c++ c++11 typetraits


【解决方案1】:

为什么会失败?

std::vector&lt;A&gt; 有一个非成员 operator== 函数模板,它与代码中 std::declval&lt;T&gt;() == std::declval&lt;T&gt;() 中的 == 匹配。所以检查成功。

该函数模板的主体无法编译的事实与 SFINAE 无关;重要的是声明是有效的。

如何解决这个问题?

我能想到的唯一方法是手动将您的特征专门用于标准容器。

【讨论】:

  • 为什么操作符== 是非成员操作符是个问题?
猜你喜欢
  • 2014-08-19
  • 2012-08-06
  • 1970-01-01
  • 2015-06-17
  • 2014-09-15
  • 1970-01-01
  • 2011-11-24
  • 2011-12-12
  • 2012-08-25
相关资源
最近更新 更多