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

陌路散爱 提交于 2021-01-27 06:57:50

问题


I am trying to explicitly instantiate a templated function of type U inside a templated class of type T. My code below generates a warning and the linker does not find the explicit instantiation of ReinterpretAs(). Can anyone spot the error or advise on how to do this? I am using 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>();

The last two lines above give a compiler warning:

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

Thank you in advance, Mark


回答1:


You're missing the 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;


来源:https://stackoverflow.com/questions/8302407/c-explicit-templated-function-instantiation-for-templated-class-of-different-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!