c++ - 有没有办法在编译时测试类型是否为 "bool operator==(const type&, const type&)"?

标签 c++

我写了一个类来测试“type == type”,但是当 type 没有运算符==时失败了;

template <typename _Type>
double _test(...){
    return 0;
}

template <typename _Type>
auto _test(_Type&& t)->decltype(t == t){
    return 0;
}

template <typename _Type>
struct has_equal_to
{
    static const bool value = sizeof(_test(std::declval<_Type>())) == sizeof(char);
};

struct test{};

int main()
{
    std::cout << has_equal_to<test>::value << std::endl; // compile failed ~~~~
    return 1;
}

有没有人可以帮忙? 或者不可能写出这样的类.....

最佳答案

你的第一个 test 重载不应该是一个模板,因为 _Type 不能被推导并且在那个上下文中无关紧要:

double _test(...){
    return 0;
}

Live Demo


您可以使用 C++17 的 std::void_t 以更少的样板实现同样的事情(您可以轻松地为 C++11 自己实现):

template <typename T, typename = void>
struct has_equal_to : std::false_type{};

template <typename T>
struct has_equal_to<T, 
         std::void_t<decltype(std::declval<T>() == std::declval<T>())>>
: std::true_type{};

Live Demo


或者您可以使用 std::experimental::is_detected甚至更少:

template <typename T>
using equal_to_t = decltype(std::declval<T>() == std::declval<T>());

template <typename T>
using has_equal_to = std::experimental::is_detected<equal_to_t, T>;

Live Demo


顺便说一句,您不应该使用以下划线开头的名称;它们保留给实现。

关于c++ - 有没有办法在编译时测试类型是否为 "bool operator==(const type&, const type&)"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38914730/

相关文章:

c++ - 虽然循环不退出,即使它应该

c++ - 使用远程线程的 DLL 注入(inject)在执行时不执行任何操作

c++ - 我可以删除和删除下面的指针列表吗

c++ - WaitCommEvent 在第二次传递时失败无效参数

c++ - 为什么 C++ STL 不实现更高效的 std::set 实现?

c++ - 使用 lex 和 yacc 构建 C++ 配置文件解析器

c++ - 当 UDP header 校验和不正确时,UDP 数据包是否被丢弃?

c++ - 引用二维 vector 中的元素 (c++)

C++11 static_assert(以及其中使用的函数)

c++ - 为什么我不能在这个专门的函数模板中将字符串文字传递给 const char* const&