我有一个模板化的C++类,其中包含一个模板化的成员函数。这个成员函数的模板参数依赖于类的模板参数以一种特定的方式(请参见下面的代码)。
我对该类进行了两个不同值的模板参数实例化(而非特化)。一切都编译通过。但是,如果调用模板化的成员函数,则仅针对第一个实例化的对象进行调用,第二个则无法编译通过。
看起来,编译器没有为模板类的第二个实例化实例化模板成员函数。我使用"g++ filename.cpp"编译以下代码,获得以下错误:
filename.cpp:63: error: no matching function for call to 'Manager<(Base)1u>::init(Combination<(Base)1u, (Dependent2)0u>*)’
这是调用b.init(&combination_2)
的行。
g++ --version => g++ (Ubuntu/Linaro 4.4.7-1ubuntu2) 4.4.7
uname -a => Linux 3.2.0-25-generic-pae #40-Ubuntu SMP i686 i686 i386 GNU/Linux
enum Base {
AA,
BB,
CC
};
enum Dependent1 {
PP,
QQ,
RR
};
enum Dependent2 {
XX,
YY,
ZZ
};
template<Base B>
struct DependentProperty {
};
template<>
struct DependentProperty<AA> {
typedef Dependent1 Dependent;
};
template<>
struct DependentProperty<BB> {
typedef Dependent2 Dependent;
};
template <Base B, typename DependentProperty<B>::Dependent D>
class Combination {
public:
void reset() {}
int o;
};
template <Base B>
class Manager {
public:
template <typename DependentProperty<B>::Dependent D,
template<Base,
typename DependentProperty<B>::Dependent> class T>
void init(T<B, D>* t);
};
template <Base B>
template <typename DependentProperty<B>::Dependent D,
template<Base,
typename DependentProperty<B>::Dependent> class T>
void Manager<B>::init(T<B, D>* t) {
t->reset();
}
int main(int argc, char** argv) {
Manager<AA> a;
Manager<BB> b;
Combination<AA, PP> combination_1;
Combination<BB, XX> combination_2;
a.init(&combination_1);
b.init(&combination_2);
return 0;
}
在我们实际的项目中,修改与我的示例代码中的Base、Dependent或Combination对应的类是不可行的。我真正想知道的是,我定义Manager::init()的语法是否有误,或者C++或g++是否存在某些已知的属性/特性/约束,不允许这段代码?