C++ - Literal class type(const constructor) as template non-type argument

less than 1 minute read

C++20 allow to have a template non type argument for literal class type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

struct Point {
  int x;
  int y;

  constexpr Point(int x, int y) : x(x), y(y) {}
};

template <Point P>
void printPoint() {
  std::cout << "Point: (" << P.x << ", " << P.y << ")" << std::endl;
}

int main() {
  printPoint<Point{1, 2}>();  // Output: Point: (1, 2)
  return 0;
}

Categories:

Updated: