非模板类,可以有模板函数么?我用VC8编译下面的代码提示错误:C/C++ code#include stdafx.hclass my{publi
非模板类,可以有模板函数么?
我用VC8编译下面的代码提示错误:
- C/C++ code
#include "stdafx.h"class my{public: my():i(2),j(3){printf("ctor\n");} ~my(){printf("dtor\n");} template<class T> vod add( T t ){ i+=t; }private int i,j;};int main(int argc,char**){ my m1; m1.add<short>(3); return 0;}1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2238: unexpected token(s) preceding ';'
1>my.cpp(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(11): error C2143: syntax error : missing ';' before '<end Parse>'
1>my.cpp(11): warning C4183: 'add': missing return type; assumed to be a member function returning 'int'
1>my.cpp(13): error C2238: unexpected token(s) preceding ';'
1>my.cpp(5): error C2614: 'my' : illegal member initialization: 'j' is not a base or member
1>my.cpp(5): error C2614: 'my' : illegal member initialization: 'i' is not a base or member
1>my.cpp(17): error C2065: 'm1' : undeclared identifier
1>my.cpp(17): error C2062: type 'short' unexpected
如果我在class 前面加上模板声明
template<class U>
使用的时候变成my<int> m1;
这次错误更多了
1>my.cpp(9): error C2146: syntax error : missing ';' before identifier 'add'
1> my.cpp(14) : see reference to class template instantiation 'my<U>' being compiled
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2238: unexpected token(s) preceding ';'
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2143: syntax error : missing ';' before '<end Parse>'
1>my.cpp(9): warning C4183: 'add': missing return type; assumed to be a member function returning 'int'
1>my.cpp(13): error C2238: unexpected token(s) preceding ';'
1>my.cpp(9): error C2146: syntax error : missing ';' before identifier 'add'
1> my.cpp(16) : see reference to class template instantiation 'my<U>' being compiled
1> with
1> [
1> U=int
1> ]
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2238: unexpected token(s) preceding ';'
1>my.cpp(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>my.cpp(9): error C2143: syntax error : missing ';' before '<end Parse>'
1>my.cpp(9): warning C4183: 'add': missing return type; assumed to be a member function returning 'int'
1>my.cpp(13): error C2238: unexpected token(s) preceding ';'
到底错在哪里呢?
[解决办法]
显然是可以的嘛。楼主敲代码要小心啊。
- C/C++ code
class my{public: my():i(2),j(3){printf("ctor\n");} ~my(){printf("dtor\n");} template<class T> void add(T t ){ i+=t; }private: int i,j;};int main(int argc,char**){ my m1; m1.add<short>(3); return 0;} 