Skip to content

Trivia impact: rare

auto Can Be a Value Template Parameter

the template argument supplies both a value and its type

template <auto Value>
void show() {
  std::cout << Value << ": "
            << std::is_same<decltype(Value), int>::value << "\n";
}

show<42>();
show<'x'>();

Does this compile? What does it print?

Answer
42: 1
x: 0

It is valid C++17: the first Value is an int, while the second is a char.

Why

[temp.param] permits a non-type template parameter whose type contains the placeholder auto; the supplied template argument deduces that type. Thus 42 makes Value an int, and 'x' makes it a char, which is why only the first type comparison prints 1. This does not make every constant value a valid C++17 template argument: the deduced type still has to meet C++17's non-type-template-parameter rules.

Where it shows up

It removes the old template <class T, T Value> boilerplate from small helpers that work with compile-time integers, enums, pointers, or nullptr. Libraries with generic value templates and generated compile-time tables use it; ordinary application templates rarely need it directly.

Takeaway: in C++17, template <auto V> deduces a non-type template parameter's type.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry