Home >Backend Development >C++ >Why Can't Strings Be Used as Non-Type Template Parameters in C ?
Why Can't Non-Type Template Parameters Be Strings?
In C , non-type template parameters must be constant integral expressions. However, the code below attempts to use a std::string as a non-type template parameter:
template <std::string temp> void foo() { // ... }
This results in a compiler error indicating that std::string is an illegal type for a non-type template parameter.
The reason for this restriction is that non-constant expressions cannot be parsed and substituted during compilation. They could change during runtime, which would require generating a new template at runtime. Since templates are a compile-time concept, this is not possible.
The C 11 standard explicitly allows only certain types for non-type template parameters:
The above is the detailed content of Why Can't Strings Be Used as Non-Type Template Parameters in C ?. For more information, please follow other related articles on the PHP Chinese website!