Home > Backend Development > C++ > Why Can't Strings Be Used as Non-Type Template Parameters in C ?

Why Can't Strings Be Used as Non-Type Template Parameters in C ?

Linda Hamilton
Release: 2024-12-13 16:28:13
Original
341 people have browsed it

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()
{
     // ...
}
Copy after login

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:

  • Integral or enumeration types
  • Pointers to objects or functions
  • Lvalue references to objects or functions
  • Pointers to members
  • std::nullptr_t

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template