Home > Article > Backend Development > Can C-Style Strings Be Template Arguments in C ?
C-Style Strings as Template Arguments
In the realm of C programming, you may have encountered a dilemma: attempting to employ C-style strings as template arguments. This article delves into the issue and a potential workaround.
The following code snippet illustrates the attempt:
<code class="cpp">template <char *str> struct X { const char *GetString() const { return str; } }; int main() { X<"String"> x; cout << x.GetString(); }
However, despite the lack of compilation errors in the class definition, the instantiation yields an error message. The issue lies in the attempt to use a string literal as a template argument, which is not supported by the compiler.
A simple solution involves replacing the string literal with a character pointer:
<code class="cpp">char global_string[] = "String"; template <char const *str> struct X { const char *GetString() const { return str; } }; int main() { X<global_string> x; cout << x.GetString(); }</code>
This code will successfully compile and execute, allowing you to retrieve the stored string using the GetString method.
Note that with the advent of C 11, it is now possible to employ string literals as template arguments using character packs. However, for compilers supporting earlier C versions, the workaround presented here remains a viable option.
The above is the detailed content of Can C-Style Strings Be Template Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!