問題描述
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();
}
雖然我沒有收到關于類定義的抱怨,但實例化會產生 'X' : invalid expression as a template argument for 'str'
(VC).
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>
) 并且它 可以將文字字符串傳遞給這樣的模板.
Update: Nowadays, a few years after this question was asked and answered, it is possible to use string literals as template arguments. With C++11, we can use characters packs as template arguments (template<char ...c>
) and it is possible to pass a literal string to such a template.
這會奏效:
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 樣式字符串作為模板參數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!