gpt4 book ai didi

C++如何实现模板化转换二元运算符重载

转载 作者:行者123 更新时间:2023-12-04 08:07:33 24 4
gpt4 key购买 nike

我正在尝试这样做:

template<class Float>
struct Number {
Float v;
Number(Float iv = 0) : v(iv) {}
};

template<class F>
Number<F> operator+(Number<F> const& a, Number<F> const& b) {
return {a.v + b.v};
}

int main() {
Number<float> y = Number<float>(1) + 2.0f;
std::cout << y.v << "\n";
}
但它不起作用。
main.cpp:15:38: error: invalid operands to binary expression ('Number<float>' and
'float')
Number<float> y = Number<float>(1) + 2.0f;
~~~~~~~~~~~~~~~~ ^ ~~~~
main.cpp:10:11: note: candidate template ignored: could not match
'Number<type-parameter-0-0>' against 'float'
Number<F> operator+(Number<F> const& a, Number<F> const& b) {
^
出于某种原因,这确实有效:
struct Number {
float v;
Number(float iv = 0) : v(iv) {}
};

Number operator+(Number const& a, Number const& b) {
return {a.v + b.v};
}

int main() {
Number x = Number(1) + 2.0f;
std::cout << x.v << "\n";
}
但我希望模板案例能够工作。基本上,我正在寻找任何类型的解决方法,使我能够为 Number 实现二进制运算符,这将允许其中一个参数可以转换为 Number。最好符合 c++14。
编辑:基于下面理查德的链接,我想出了这个似乎可以处理多次转换的情况,但不幸的是,每个运算符都需要 3 个重载:
template<class T>
struct identity {
using type = T;
};

template<class T>
using convertible = typename identity<T>::type;

template<class Float>
struct Param {
Float v;
};

template<class Float>
struct Number {
Float v;
Number(Float iv = 0) : v(iv) {}
Number(Param<Float> iv) : v(iv.v) {}
};

template<class F>
Number<F> operator+(Number<F> const& a, Number<F> const& b) {
return {a.v + b.v};
}
template<class F>
Number<F> operator+(Number<F> const& a, convertible<Number<F>> const& b) {
return {a.v + b.v};
}
template<class F>
Number<F> operator+(convertible<Number<F>> const& a, Number<F> const& b) {
return {a.v + b.v};
}

int main() {
std::cout << (Number<float>{1} + 2).v << "\n";
std::cout << (Number<float>{1} + Param<float>{2}).v << "\n";
std::cout << (Param<float>{1} + Number<float>{2}).v << "\n";
std::cout << (Number<float>{1} + Number<float>{2}).v << "\n";
std::cout << (1 + Number<float>{2}).v << "\n";
}

最佳答案

template argument deduction 中不会考虑隐式转换.

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.


所以模板参数 F的推导第二个函数参数失败 bNumber(1) + 2.0f ,来自 float 的隐式转换至 Number<float>不会考虑。
您可以添加另外两个重载作为
template<class F, class V>
Number<F> operator+(Number<F> const& a, V const& b) {
return {a.v + Number{b}.v};
}

template<class F, class V>
Number<F> operator+(V const& a, Number<F> const& b) {
return {Number{a}.v + b.v};
}
LIVE

关于C++如何实现模板化转换二元运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66147907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com