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

标签 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>();

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

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

提前谢谢你,马克

最佳答案

您缺少 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;

关于C++ 不同类型模板化类的显式模板化函数实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8302407/

相关文章:

c++ - g++ 和 msvc 中的 std::uniform_int_distribution<int> 范围

windows - 是否有必要在退出 Win32 应用程序之前显式停止所有线程?

c++ - Is i = (0,++i, 0) 未定义行为

c++ - 如何将 CPoint 对象转换为字符串?

c++ - 是否有设计好的类模板的通用规则?

c++ - 继承依赖的 typedef 而不使用 struct

c++ - 使用SFINAE计算不同元素的大小

c++ - 数组的资源泄漏

c++ - Excel C API : Is there an Excel v4. 0 用于测试工作表是否被隐藏的宏函数?

c++ - 双重乘法给出四舍五入的结果