重载内置类型的运算符

重载内置类型的运算符

问题描述:

虽然我将一些代码编写为像python和其他语言中已知的power-operator的实现一样的语法糖,但运算符定义可以,但操作数与运算符签名匹配的表达式产生一个错误,因为操作员从未被定义过。有没有一种方法(编译器选项)为内置类型实现新的运算符?重载内置类型的运算符

#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甚至不支持运算符的定义。

+0

有一个在C++中没有'**'经营者,如果你期待的是要幂像Python中,你应该使用'STD :: pow'或编写自己的函数 – CoryKramer

+0

@CoryKramer但是,当使用用户定义的类型而不是double并将数字转换为此类型时,此处定义的权力运算符起作用(它实际上是两个运算符,即* -prefix运算符和乘法运算符!) – cmdLP

你现在要问的是不可能的。您不能为内置插件重载运算符。因此,您的第一次过载是非法的,因为您正在尝试为double定义一元operator*。不知道为什么海湾合作委员会不抱怨。

但是,您可以使用UDL来“改变”文字的类型。下面是演示一个简单的例子:

struct Exponent { long double value; }; 
struct PowerDouble { long double value; }; 

Exponent operator""_exp(long double exponent) { 
    return{exponent}; 
} 

PowerDouble operator*(Exponent f) { 
    return{f.value}; 
} 

long double operator*(long double l, PowerDouble r) { 
    return std::pow(l, r.value); 
} 

long double operator*(long double l, Exponent r) { 
    return l * r.value; 
} 

然后你可以使用它像这样:

std::cout << 10.5 ** 2._exp << '\n'; 
std::cout << 10.5 * 2._exp << '\n'; 
+0

请注意,对此,“10.5 * 2._exp”也将执行幂运算。就像'10.5 ***** 2._exp'一样。 –

+0

@BenjaminLindley你是对的,修好:)谢谢 – Rakete1111

不,你不能重载,唯一的参数是内置类型的操作。即使该运营商不存在所述类型。

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

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