Question:
Can a string literal be passed as a non-type argument to a class template, such as in a declaration like my_class<"string">?
Answer:
While directly passing string literals as non-type template arguments is not possible, there is a solution that closely approximates it.
You can utilize a non-type template parameter of type const char* and pass it a const char[] variable with static linkage. This approach shares similarities with passing string literals directly.
Here's a compilable example:
#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(); }
The above code declares a class template cts with a non-type template parameter str that takes a constant character pointer. The variable teststr, defined with static linkage, holds the string literal and is passed to the template instantiation.
This method is a viable alternative to directly passing string literals as non-type template arguments.
The above is the detailed content of Can String Literals be Passed as Non-Type Template Arguments?. For more information, please follow other related articles on the PHP Chinese website!