Home > Article > Backend Development > Can C-Style Strings Be Used as Template Arguments in C ?
Can C-Style Strings Be Template Arguments?
Your attempt to instantiate a template using a C-style string fails with an error due to the invalid use of a string literal as a template argument.
While C-style strings cannot directly serve as template arguments, there are alternative approaches:
Use a Pointer to a Constant String
One workaround is to use a pointer to a constant string as the template argument:
<code class="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(); }
Update: String Literals as Template Arguments with C 11
With C 11 and later, it is possible to use string literals as template arguments by utilizing character packs:
<code class="c++">template <char ...c> struct X { const char (*GetString)() { return [](char*... s) { return s; }(c...); } }; int main() { X<"S", "t", "r", "i", "n", "g"> x; cout << x.GetString(); }</code>
The above is the detailed content of Can C-Style Strings Be Used as Template Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!