努力 select 使用模板结构的类型

Struggling to select a type using a templated structure

我有一个这样声明的结构:

template <typename T, typename U> struct select_type;

我专门研究它:

template <> struct select_type<float, double>
{
  typedef double type;
};

对于 <double, float><int, float>...

等几种类型依此类推

我在我的一些模板函数中使用它,例如:

template <typename T, typename U, typename select<T,U>::type R >
smu::Matrix<R> operator*(const smu::Matrix<T>& a, const smu::Matrix<U>& b)
{
/* code here */
}

我尝试了几种使用它的方法,没有 R,没有 typename,但大多数时候我在请求 nested-name parameter before select 时出错。事实是我从来没有这样做过,我不知道我应该如何使用这个结构。谁能帮我解决这个问题?

template <typename T, typename U>
smu::Matrix<typename select<T, U>::type> operator*(
    const smu::Matrix<T>& a, const smu::Matrix<U>& b)

这里有一些错误。您声明 R:

的方式
typename select<T,U>::type R 

是类型 select<T,U>::type。这不是您想要的 - 您希望 R 成为 类型 。其次,R 是一个非推导上下文——它是一个模板参数,未在任何参数中指定,因此无法推导,只能明确指定。但是你也不能真正明确地指定它,因为无论如何这都违背了方便 operator* 的目的。

在 C++11 及更高版本中,您可以将其设为 默认 类型参数:

template <typename T, typename U, typename R = typename select<T,U>::type>
smu::Matrix<R> operator*(const smu::Matrix<T>& a, const smu::Matrix<U>& b)

但是在C++03中,你不能有默认的函数模板参数,所以你只需要写出来:

template <typename T, typename U>
smu::Matrix<typename select<T,U>::type> operator*(const smu::Matrix<T>& a,
    const smu::Matrix<U>& b)
{
    typedef typename select<T,U>::type R;

    /* rest as before */
}