C++中如何显式实例化模板类/结构体的模板构造函数
模板构造函数的显式实例化问题
我定义了一个带模板构造函数的模板结构体:
template<typename F> struct Vector2 { template<typename F1> Vector2(const Vector2<F1>& vector); };
对应的实现代码:
template<typename F> template<typename F1> Vector2<F>::Vector2(const Vector2<F1>& vector) : Vector2(vector.x, vector.y) {}
我想针对Vector2<float>和Vector2<double>类型,显式实例化这个模板构造函数,让它们能互相转换,但尝试了几种写法都报错:
template struct Vector2<float>::Vector2(const Vector2<float>& vector); // 错误:"Expected unqualified-id" 和 "Expected ')'
template struct Vector2<float>::Vector2<float>(const Vector2<float>& vector); // 错误:与上一个相同
template struct Vector2::Vector2(const Vector2<float>& vector); // 错误:"Use of class template 'Vector2' requires template arguments"
template Vector2<float>::Vector2(const Vector2<float>& vector); // 错误:"Explicit instantiation refers to member function 'Vector2<float>::Vector2' that is not an instantiation"
正确的显式实例化写法
要显式实例化模板类中的模板构造函数,必须同时指定外层类模板的参数和内层构造函数模板的参数,语法格式如下:
// 实例化 Vector2<float> 接收 Vector2<double> 的构造函数 template Vector2<float>::Vector2<double>(const Vector2<double>&); // 实例化 Vector2<double> 接收 Vector2<float> 的构造函数 template Vector2<double>::Vector2<float>(const Vector2<float>&); // 如果需要同类型的构造函数(比如 Vector2<float> 接收 Vector2<float>) template Vector2<float>::Vector2<float>(const Vector2<float>&);
错误原因说明
- 前两种写法用了
template struct,但构造函数是成员函数,显式实例化成员函数不需要加struct,直接用template开头即可。 - 第三种写法没有给外层
Vector2模板指定参数,违反了模板类的使用规则。 - 第四种写法缺少内层构造函数的模板参数
F1,编译器无法确定要实例化哪个版本的模板构造函数,因此报错。
内容的提问来源于stack exchange,提问作者dan2978
相关产品推荐
相关产品推荐

