The*_*ang 5 c++ templates arithmetic-expressions c++11 type-promotion
如果我有一个通用的struct/class:
template<typename T>
struct Container
{
T value;
Container(const Value& value) : value(value) { }
};
Run Code Online (Sandbox Code Playgroud)
我想对其中两个执行操作:
template<typename T, typename U>
Container<T> operator+(const Container<T>& lhs, const Container<U>& rhs)
{
return Container<T>(lhs.value + rhs.value);
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果lhs是类型Container<int>和rhs类型Container<float>,那么我会Container<int>回来.但是,如果我这样做auto result = 2 + 2.0f,那么result就是那种类型float.因此内置类型和自定义类型之间的行为不一致.
那么我将如何处理operator+重载并使其返回Container<float>,就像C++如何使用内置类型处理算术推广一样?
只要您使用两种类型的模板中的一种,就有可能对总和的结果进行强制转换.例如,如果您不小心选择int了目标类型,即使总和结果为a float,它也会被转换为所选类型.
无论如何,从C++ 11开始,您可以依赖于decltype上面示例中的说明符(或者至少,如果Container::T并且是定义运算符Container::U的类型,则可以这样做+).
我还使用了auto说明符作为返回值operator+,因为它可以从C++ 14开始使用,它确实非常有用.
它遵循上面提到的工作示例:
#include <iostream>
#include <vector>
template<typename T>
struct Container
{
T value;
Container(const T& value) : value(value) { }
};
template<typename T, typename U>
auto operator+(const Container<T>& lhs, const Container<U>& rhs)
{
return Container<decltype(lhs.value+rhs.value)>{lhs.value + rhs.value};
}
int main()
{
Container<int> c1{1};
Container<float> c2{0.5};
std::cout << (c1+c2).value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)