【发布时间】:2012-06-25 19:45:18
【问题描述】:
当模板参数与类的类型相同时,我有一个需要专门构造函数的模板类。下面的代码不会编译。
当类型为 Dual 时,指定使用特定构造函数的正确语法是什么?特别是,当模板参数的类型为 Dual 时,我需要在初始化器列表中初始化成员 'real',但如果不是(例如 double 类型)则不需要。
template<class X> class Dual {
public:
X real;
size_t N;
std::vector<X> imag;//don't know N at compile time
Dual(size_t _N);
};
template <class X>
inline Dual<X>::Dual(size_t _N): N(_N), imag(N, 0.0) {}
template <class X>
inline Dual<Dual<X> >::Dual(size_t _N): real(_N), N(_N), imag(_N, 0.0) {}
//syntax error:
//error: cpptest.cpp:20:24: error: C++ requires a type specifier for all declarations
//inline Dual<Dual<X> >::Dual(size_t _N): real(_N), N(_N), imag(_N, 0.0) {}
//~~~~~~
int main(){
Dual <double> a(5);
Dual< Dual < double>> b(5);
}
【问题讨论】:
-
相关但非直接原因:您没有默认构造函数。您如何处理没有默认构造函数的类型的默认构造,就像在嵌套声明中所做的那样?
-
这就是我试图通过专业化解决的问题。 X 类型要么是 Dual
,它需要调用 1 参数构造函数,要么是某种浮点类型,在这种情况下它不需要(值稍后分配)。 -
那么应该很明显:将默认构造函数添加到您的
Dual类。 -
带有模板参数 Dual
的默认构造函数将使对象保持一半初始化(参数给出了包含向量的大小)。
标签: c++ templates template-specialization explicit-specialization