C样式字符串作为模板参数?
问题描述:
可以使用C样式字符串作为模板参数吗?
Can C-Style strings be used as template arguments?
我试过:
template <char *str>
struct X
{
const char *GetString() const
{
return str;
}
};
int main()
{
X<"String"> x;
cout<<x.GetString();
}
虽然我没有关于类定义的投诉, c $ c>'X':无效的表达式作为'str'
And although I get no complaints about the class definition, the instantiation yields 'X' : invalid expression as a template argument for 'str'
(VC).
答
更新:现在,几年这个问题被问及回答,可以使用字符串文字作为模板参数。使用C ++ 11,我们可以使用字符包作为模板参数( template< char ... c>
)和它可以将一个文字字符串传递给这样的模板。
template <char const *str>
struct X
{
const char *GetString() const
{
return str;
}
};
char global_string[] = "String";
int main()
{
X<global_string> x;
cout<<x.GetString();
}