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).
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With