C++显式模板化函数实例化,用于不同类型的模板化类

Mar*_*ark 4 c++ templates visual-c++

我试图在类型T的模板化类中显式实例化类型U的模板化函数.下面的代码生成警告,链接器找不到显式实例化ReinterpretAs().任何人都可以发现错误或建议如何做到这一点?我正在使用VC++ 2010.

template<typename T> 
class Matrix
{
  public:
    template<typename U> Matrix<U> ReinterpretAs() const;
};

template<typename T>
template<typename U>
Matrix<U> Matrix<T>::ReinterpretAs() const
{
   Matrix<U> m;
   // ...
   return m;
}


// Explicit instantiation.
template class Matrix<int>;
template class Matrix<float>;

template Matrix<float>  Matrix<int>::ReinterpretAs<float>();
template Matrix<int>    Matrix<float>::ReinterpretAs<int>();
Run Code Online (Sandbox Code Playgroud)

上面的最后两行给出了编译器警告:

warning #536: no instance of function template "Matrix<T>::ReinterpretAs 
[with T=float]" matches the specified type
Run Code Online (Sandbox Code Playgroud)

马克,提前谢谢你

Pub*_*bby 9

你错过了const.

template class Matrix<int>;
template class Matrix<float>;

template Matrix<float>  Matrix<int>::ReinterpretAs<float>() const;
template Matrix<int>    Matrix<float>::ReinterpretAs<int>() const;
Run Code Online (Sandbox Code Playgroud)