[c++] Variable templates

In C++, variable templates allow programmers to define variables that can be parameterized. They were introduced in C++14 and provide a way to define parametric constants. Variable templates are similar to function templates, but instead of defining a parameterized function, a parameterized variable can be defined.

Basic Syntax

The basic syntax for defining a variable template is:

template <typename T>
constexpr T variable_template_name = initial_value;

Here’s an example of defining a variable template:

template <typename T>
constexpr T pi = T(3.1415926535897932385);

In this example, we define a variable template pi that is parameterized by type T and initialize it with the value of π.

Using Variable Templates

Variable templates can be used in a similar manner to regular variables. When using a variable template, the compiler will deduce the template argument from the context in which the variable is used. For example:

double circle_area(double radius) {
    return pi<double> * radius * radius;

In the above code, we use the pi variable template with double as the template argument to calculate the area of a circle.

Variable templates are particularly useful when we need to define constant values that depend on a type parameter, without the need for separate explicit specialization for each type.


Variable templates in C++ provide a powerful tool for defining parameterized constants. They offer flexibility and expressiveness, allowing programmers to define constants that depend on type parameters. By using variable templates, it’s possible to write more generic and reusable code.

For more information, refer to the C++ reference.

위 내용은 C++의 변수 템플릿에 대한 기본적인 내용과 사용법에 대해 설명하고 있습니다. 변수 템플릿은 C++14에서 도입되어 파라미터화된 상수를 정의하는 데 사용됩니다. 내용에 대한 자세한 정보는 C++ 레퍼런스를 참조하십시오.