【发布时间】:2013-01-25 09:27:01
【问题描述】:
我有一个模板化的 C++ 类,它也有一个模板化的成员函数。这个成员函数的模板参数以特定的方式依赖于类的模板参数(请看下面的代码)。 我正在为它的模板参数的两个不同值实例化(不是专门化)这个类。一切都编译到这一点。但是,如果我调用模板化成员函数,则仅对第一个实例化对象的调用会编译,而不是第二个。 似乎编译器没有为模板类的第二次实例化实例化模板化成员函数。我正在使用“g++ filename.cpp”编译下面的代码并收到以下错误:
filename.cpp:63: error: no matching function for call to 'Manager::init(Combination*)'
这是调用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++ 的属性/功能/约束不允许此代码?
【问题讨论】:
-
在定义模板函数 init() 之前使用
typedef会是明智的。typename DependentProperty<B>::Dependent重复了两遍,真的无助于理解。 -
我不是 100% 确定,但这可能是编译器的错误