我写了一个类来测试“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;
}
您可以使用 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{};
或者您可以使用 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>;
顺便说一句,您不应该使用以下划线开头的名称;它们保留给实现。
关于c++ - 有没有办法在编译时测试类型是否为 "bool operator==(const type&, const type&)"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38914730/