c++ - 重载内置类型的运算符

标签 c++ operator-overloading

<分区>

虽然我正在编写一些代码作为语法糖,例如 python 和其他语言中已知的幂运算符的实现,运算符定义是可以的,但是操作数与运算符签名匹配的表达式会产生错误,如运营商从未被定义。有没有办法(编译器选项)为内置类型实现新的运算符?

#include <iostream>
#include <cmath>

    template<typename t_Float>
struct PowerTmp {
    t_Float value;
};

PowerTmp<double> operator*(double f) {
    return {f};
};

double operator*(double l, PowerTmp<double> r) {
    return std::pow(l, r.value);
};

int main() {
    std::cout << 10.5 *PowerTmp<double>{2.0} << '\n';
    cout << 10.5 ** 2.0 << '\n'; //error
};

我正在使用 mingw。

编辑:clang 甚至不支持运算符的定义。

最佳答案

不,您不能重载唯一参数是内置类型的运算符。即使该运算符对于所述类型不存在。

您可以做的是创建一个中介类型。例如:

struct EnhancedDouble {
    double d;
};

struct PowPrecursor {
    double d;
};

PowPrecursor operator*(EnhancedDouble b) {
    return { b.d };
}

EnhancedDouble operator*(EnhancedDouble lhs, PowPrecursor rhs) {
    return { std::pow(lhs.d, rhs.d) };
}

您甚至可以使用用户定义的字面量来加糖。

EnhancedDouble operator""_ed(long double d) {
    return { (double)d };
}

投入 operator<<你可以这样做:

std::cout << 4.0_ed ** 4.0_ed; // prints 256

关于c++ - 重载内置类型的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45307180/

相关文章:

c++ - 将键值对文件读入 std::map

c++ - 没有合适的用户定义转换

c++ - 使用引用传递的指针重载

swift - 在 Swift 中重载运算符

c++ - 重载 "function call"运算符有什么用处?

c++ - 序列化包含指针 vector 的结构,每个指针包含其他指针

C++11 非拥有引用/指向 unique_ptr 的指针?

c++ - 2 个不同对象的交换运算符重载 +

当写在一行中时,C++ move 构造函数不使用复合运算符 += 调用

c++ - 游戏协议(protocol)