我从具有部分特化的模板继承,我不能从派生的ctor中调用模板ctor。
当下面代码中的部分特化被注释掉时,它会编译而没有任何错误或警告。
#include <iostream>
typedef enum {supertype, subtype} selector;
template< typename T, selector s>
class Tmpl {
protected:
T* root;
public:
Tmpl( T* t = 0 ) {
root = t;
}
T listHead( ) {
std::cout << "template listHead() called" << std::endl;
}
};
class Descriptor {
public:
Descriptor( const char * s ) {
std::cout << "Descriptor " << s << std::endl;
}
};
// partial specialization - if uncommented, errors
// are reported at the supertypesIterator ctor below.
/*
template<selector s>
class Tmpl<Descriptor, s> {
public:
Descriptor listHead( ) {
switch( s ){
case supertype:
return Descriptor("Supertypes");
case subtype:
return Descriptor("Subtypes");
}
}
};
*/
class supertypesIterator : public Tmpl<Descriptor, supertype> {
public:
supertypesIterator( Descriptor* t = 0 ):Tmpl<Descriptor, supertype>(t) {}
};
main() {
supertypesIterator s;
s.listHead();
}
如果我取消注释专业化,我会收到以下错误:
$ g++ trouble.cc
trouble.cc: In constructor ‘supertypesIterator::supertypesIterator(Descriptor*)’:
trouble.cc:43:74: error: no matching function for call to ‘Tmpl<Descriptor, (selector)0u>::Tmpl(Descriptor*&)’
trouble.cc:43:74: note: candidates are:
trouble.cc:27:7: note: Tmpl<Descriptor, (selector)0u>::Tmpl()
trouble.cc:27:7: note: candidate expects 0 arguments, 1 provided
trouble.cc:27:7: note: Tmpl<Descriptor, (selector)0u>::Tmpl(const Tmpl<Descriptor, (selector)0u>&)
trouble.cc:27:7: note: no known conversion for argument 1 from ‘Descriptor*’ to ‘const Tmpl<Descriptor, (selector)0u>&’
我需要做些什么才能从supertypesIterator
ctor中初始化基类?
我正在使用g ++版4.7.1
,但我还需要这个才能跨平台工作。
答案 0 :(得分:2)
您必须在专业化中实现缺少的构造函数。否则,supertypesIterator
的构造函数正在尝试调用不存在的Tmpl
构造函数。
template<selector s>
class Tmpl<Descriptor, s> {
Descriptor* root;
public:
Tmpl( Descriptor* t = 0 ) {
root = t;
}
Descriptor listHead( ) {
switch( s ){
case supertype:
return Descriptor("Supertypes");
case subtype:
return Descriptor("Subtypes");
}
}
};