Home > Article > Backend Development > Can String Literals Be Used as Non-Type Template Parameters in C ?
Class Templates with Non-Type String Literals
In C , you may encounter the need to declare class templates with non-type parameters, such as string literals. This query explores the feasibility of this approach and provides a solution.
Non-Type Template Parameter Rationale
You might wish to utilize string literals directly as non-type template parameters for convenience or readability purposes. However, this is not directly supported in C .
A Feasible Workaround
While passing a string literal directly is not possible, a workaround involves using a const char* non-type template parameter and passing it a const char[] variable with static linkage. This method is nearly equivalent to passing a string literal.
Example Implementation
The following code demonstrates this workaround:
#include <iostream> template<const char *str> struct cts { void p() {std::cout << str;} }; static const char teststr[] = "Hello world!"; int main() { cts<teststr> o; o.p(); }
Explanation
Conclusion
This workaround allows you to effectively use string literals in class templates as non-type parameters. It provides an alternative solution when direct string literal input is not feasible.
The above is the detailed content of Can String Literals Be Used as Non-Type Template Parameters in C ?. For more information, please follow other related articles on the PHP Chinese website!