模板中非类型参数的限制
- C/C++ code
//函数模板定义:template <ofstream &of,class T>ofstream &func(T t){ of<<t<<endl; return of; }//of定义为全局变量:ofstream of("out.txt");//调用时,即将5输入到文件中!func<of,int>(5);
关于of的问题,查资料说 :非类型参数必须在编译时就确定其值,但是我将of在main函数中定义为static ofstream of("out.txt");或者定义为全局的static ofstream of("out.txt")都会出问题!
赐教!!
[解决办法]
除整形以外,其他的不要作为非类型模板参数。
[解决办法]
14.3.2 Template non-type arguments [temp.arg.nontype]
1 A template-argument for a non-type, non-template template-parameter shall be one of:
— an integral constant-expression of integral or enumeration type; or
— the name of a non-type template-parameter; or
— the address of an object or function with external linkage, including function templates and function
template-ids but excluding non-static class members, expressed as & id-expression where the & is
optional if the name refers to a function or array, or if the corresponding template-parameter is a reference;
or
— a pointer to member expressed as described in 5.3.1 .
external linkage 知道什么意思吧?