c++ - has_equal_operator 在 C++11 中的实现

标签 c++ c++11 typetraits

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

相关文章:

c++ - 对二维结构数组进行排序

c++ - 如何去除这种循环依赖

c# - 可以使用 Boost 或 STL 显示自定义字符串的 C++ 断言?

c++ - 表达式 SFINAE 重载传递函数指针的类型

C++ 缓冲区的痛苦

c++ - 如何将 std::enable_if 与自推断返回类型一起使用?

c++ - 如何调试由类型特征引起的这个错误?

c++ - 显示二维数组图像的最佳 C++ 库

C++11 无法移动内部有 unordered_map 的类

c++ - 为什么 std::remove_const 不删除 const 限定符?