在 C++11 中,您可以像这样利用内置类型提升:
#include <type_traits>
class IntegerVector;
class RealVector;
template <class T> struct VectorForType {};
template <> struct VectorForType<int> {typedef IntegerVector type;};
template <> struct VectorForType<double> {typedef RealVector type;};
// This is where we figure out what C++ would do..
template <class X, class Y> struct VectorForTypes
{
typedef typename VectorForType<decltype(X()*Y())>::type type;
};
class IntegerVector
{
public:
template <class T> struct ResultVector
{
typedef typename VectorForTypes<int, T>::type type;
};
template <class T>
typename ResultVector<T>::type operator*(const T scalar) const;
};
class RealVector
{
public:
template <class T> struct ResultVector
{
typedef typename VectorForTypes<double, T>::type type;
};
RealVector();
RealVector(const IntegerVector &other);
template <class T>
typename ResultVector<T>::type operator*(const T scalar) const;
};
int main()
{
IntegerVector v;
auto Result=v*1.5;
static_assert(std::is_same<decltype(Result), RealVector>::value, "Oh no!");
}
如果你不需要 decltype,你也可以将类型提升结果实现为元函数。我想一个运算符实现看起来像这样:
template <class T> inline
typename ResultVector<T>::type IntegerVector::operator*(const T scalar) const
{
typename ResultVector<T>::type Result(this->GetLength());
for (std::size_t i=0; i<this->GetLength(); ++i)
Result[i]=(*this)*scalar;
return Result;
}