小编cou*_*age的帖子

为没有运算符>的类添加运算符>在不同编译器上会显示不同的结果

最近,我编写了一些实验代码,为所有没有运算符的类添加运算符>。代码在这里:

#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)

c++ templates language-lawyer

5
推荐指数
0
解决办法
106
查看次数

标签 统计

c++ ×1

language-lawyer ×1

templates ×1