【发布时间】:2012-10-21 21:26:45
【问题描述】:
类模板中的模板构造函数 - 如何为第二个参数显式指定模板参数?
尝试为构造函数 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):“错误:shadows template parm 'class T'”。与void foo()相同。当我将T替换为例如X,我可以让它工作。 -
您使用的是哪个编译器?我什至无法编译你的代码
-
@gogoprog 你不是唯一的。
-
gcc 说明了一切,VC10 再次被证明是愚蠢的!