【发布时间】:2016-01-24 05:29:15
【问题描述】:
如果我有一个通用结构/类:
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);
}
问题是如果lhs 是Container<int> 类型并且rhs 是Container<float> 类型,那么我会得到一个Container<int> 回来。但如果我要执行auto result = 2 + 2.0f,那么result 将属于float 类型。所以内置类型和自定义类型的行为是不一致的。
那么我将如何处理 operator+ 重载并使其返回 Container<float>,就像 C++ 如何使用内置类型处理算术提升一样?
【问题讨论】:
-
@PiotrSkotnicki 是的。
标签: c++ templates c++11 arithmetic-expressions type-promotion