模板怎样传递字符串参数?
我的模板类需要传递一个字符串作为参数,但是我试验了很多不行啊,求教大虾。
刚开始的时候,我这样写
template<CString strTest> class CMyTest{....};
然后再stdAfx.h中加入了
CMyTest<CString("kfsad")> g_myTest;
可是编译时报错说:
error C2993: 'strTest' : template parameter can never be initialized
error C2973: 'CMyTest' : invalid template argument 'strTest'
然后我就改成:
template<class TYPE, char* pchTest> class CMyTest{....};
再stdAfx.h中加入了
char* g_pchTest = "fdsjakfas";
CMyTest<g_pchTest> g_myTest;
然而编译说
error C2975: 'CMyTest' : invalid template argument for 'pchTest', constant expression expected
error C2079: 'g_myTest' uses undefined class 'CMyTest<&char * g_pchTest>'
然后我就改成
char g_pchTest[] = "fdsjakfas";
CMyTest<g_pchTest> g_myTest;
这两句如果不是加在stdafx.h中,就是可以用的,编译通过而且运行正常。但是现在我要求g_myTest在各个文件中都可以使用,这样当在其他文件中定义它时(使用extern)却会发生n多的错误。
请教如何达到此目的。
或者说如果想在类中定义一个类似g_myTest的成员变量,应该如何进行呢?根本问题还是如何传递一个字符串作为参数给模板。