Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-type template parameters

Tags:

c++

templates

I understand that the non-type template parameter should be a constant integral expression. Can someone shed light why is it so ?

template <std::string temp> void foo() {      // ... } 
error C2993: 'std::string' : illegal type for non-type template parameter 'temp'. 

I understand what a constant integral expression is. What are the reasons for not allowing non-constant types like std::string as in the above snippet ?

like image 516
Mahesh Avatar asked Apr 16 '11 15:04

Mahesh


People also ask

What are non-type parameters for templates?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type.

What is a non-type parameter in templates C++?

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.

What is template type parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.


1 Answers

The reason you can't do this is because non-constant expressions can't be parsed and substituted during compile-time. They could change during runtime, which would require the generation of a new template during runtime, which isn't possible because templates are a compile-time concept.

Here's what the standard allows for non-type template parameters (14.1 [temp.param] p4):

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std::nullptr_t.
like image 61
Xeo Avatar answered Sep 20 '22 23:09

Xeo