最近,我编写了一些实验代码,为所有没有运算符的类添加运算符>。代码在这里:
#include <cstdio>
#include <experimental/type_traits>
#include <type_traits>
struct A {
A(int x) : x(x) {}
int x;
bool operator<(const A &rhs) const {
printf("original lt\n");
return x < rhs.x;
}
};
template <class T> using gt_t = decltype(std::declval<T>() > std::declval<T>());
template <class Key>
std::enable_if_t<!std::experimental::is_detected<gt_t, Key>::value, bool>
operator>(const Key &lhs, const Key &rhs) {
printf("generated gt\n");
return rhs < lhs;
}
int main() {
A a(1);
A b(2);
printf("%d\n", b > a);
}
Run Code Online (Sandbox Code Playgroud)
我使用“-O2 -std=c++14”进行编译,gcc 8.1及更高版本编译成功,而gcc 7.5及更早版本生成编译错误(godbolt链接),例如
<source>: In …Run Code Online (Sandbox Code Playgroud)