我有一个模板类,当模板参数与类的类型相同时,它需要一个专门的构造函数。下面的代码不会编译。
当类型为 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);
}