类模板中的模板构造函数 - 如何显式指定第二个参数的模板参数?
当尝试显式指定构造函数2的模板参数时,会出现编译错误。如果我真的想要显式调用构造函数2,该怎么办?
请注意,在想要显式指定删除器类型时,boost::shared_ptr也会出现同样的情况。
注意:对于非构造函数foo(),显式指定可以正常工作。
注意:我知道在构造函数2中不显式指定第二个参数的模板参数通常也能正常工作,因为模板参数推导通常可以正常工作,我只是好奇如何显式指定它。
template<class T> class TestTemplate {
public:
//constructor 1
template<class Y> TestTemplate(T * p) {
cout << "c1" << endl;
}
//constructor 2
template<class Y, class D> TestTemplate(Y * p, D d) {
cout << "c2" << endl;
}
template<class T, class B>
void foo(T a, B b) {
cout << "foo" << endl;
}
};
int main() {
TestTemplate<int> tp(new int());//this one works ok call constructor 1
//explicit template argument works ok
tp.foo<int*, string>(new int(), "hello");
TestTemplate<int> tp2(new int(),2);//this one works ok call constructor 2
//compile error when tried to explicit specify template argument for constructor 2
//How should I do it if I really want to explicit call constructor 2?
//TestTemplate<int*, int> tp3(new int(), 2); //wrong
//TestTemplate<int*> tp3<int*,int>(new int(), 2); //wrong again
return 0;
}
tempate<class T> TestTemplate(T * p)
会导致错误(gcc 4.6.3):"error: shadows template parm 'class T'"。使用void foo()
同样会出现相同的问题。当我将T
替换为例如X
时,就可以解决这个问题。 - Olaf Dietsche