如何像内置类型一样提升两个模板类型进行算术运算呢?

How to promote two template types for arithmitic operations like builtin types do?

如果我有一个通用的 struct/class:

template<typename T>
struct Container
{
    T value;
    Container(const Value& value) : value(value) { }
};

我想对其中两个执行操作:

template<typename T, typename U>
Container<T> operator+(const Container<T>& lhs, const Container<U>& rhs)
{
    return Container<T>(lhs.value + rhs.value);
}

问题是,如果lhsContainer<int>类型,rhsContainer<float>类型,那么我会得到一个Container<int> 背部。但是,如果我要执行 auto result = 2 + 2.0f,那么 result 将是 float 类型。因此内置类型和自定义类型之间的行为不一致。

那么我如何使用 operator+ 重载并使其成为 return Container<float>,就像 C++ 如何处理内置类型的算术提升一样?

就您使用两种类型模板中的一种而言,您可能会冒着对总和结果进行强制转换的风险。例如,如果您不小心选择 int 作为您的目标类型,即使总和结果为 float,它也会被强制转换为所选类型。

无论如何,从 C++11 开始,您可以像上面的示例一样依赖 decltype 说明符(或者至少,如果 Container::TContainer::U 是定义了 + 运算符的类型。

我还使用 auto 说明符作为 operator+ 的 return 值,因为它从 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;
}