不同类型模板化类的显式模板化函数实例化

C++ Explicit templated function instantiation for templated class of different type

本文关键字:函数 实例化 同类型      更新时间:2023-10-16

我试图在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>();

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

warning #536: no instance of function template "Matrix<T>::ReinterpretAs 
[with T=float]" matches the specified type

提前感谢Mark

你错过了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;