Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C-Style Strings as template arguments? [duplicate]

Can C-Style strings be used as template arguments?

I tried:

template <char *str> struct X {     const char *GetString() const     {          return str;     } };  int main() {     X<"String"> x;     cout<<x.GetString(); } 

And although I get no complaints about the class definition, the instantiation yields 'X' : invalid expression as a template argument for 'str' (VC).

like image 765
cvb Avatar asked Dec 01 '09 14:12

cvb


1 Answers

A string literal cannot be used as a template argument.

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.

This would work, however:

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(); } 
like image 77
moonshadow Avatar answered Sep 21 '22 18:09

moonshadow