C-Style 字符串可以用作模板参数吗?
我试过了:
template <char *str>
struct X
{
const char *GetString() const
{
return str;
}
};
int main()
{
X<"String"> x;
cout<<x.GetString();
}
虽然我对类定义没有任何提示,但实例化会产生 'X' : invalid expression as a template argument for 'str'
(VC)。
最佳答案
A string literal cannot be used as a template argument .
更新:如今,在这个问题被问及回答几年后,可以使用字符串文字作为模板参数。使用 C++11,我们可以使用字符包作为模板参数 (template<char ...c>
) 和 is possible将文字字符串传递给这样的模板。
但是,这会起作用:
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();
}
关于c++ - C 样式字符串作为模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1826464/