在学习和试验模板时,我遇到了一些我无法完全掌握的东西.
class sample { public: sample(int a = 0) {} }; templatevoid add(T1 a) // Replace T1 with T2 resolves compilation error. {} int main() { add (3); return 0; }
上面的代码导致编译错误(03和c ++ 0x).但是当我将添加的参数类型从T1更改为T2时,它就可以了.对于nm,创建的原型是add(sample,int)[T1 = sample,T2 = int].为什么编译失败,T1作为参数类型而不是T2?
有两种方法可以指定模板参数:显式或隐式.
这将是明确的:
templatevoid do_something(T value) {}; do_something (6); // T is float
这将是隐含的:
int x; do_something(x); // since first argument is T and x is int, T is int
在你的情况下:
templatevoid add(T1 a); add (3); // T1 is explcitly sample, T2 is unknown
案例2:
templatevoid add(T2 a); add (3); // T1 is explcitly sample, T2 is implicitly int