C++14中变量模版的使用

      C++14中的variable template(变量模版)用于定义一系列变量或静态数据成员,语法如下:

template < parameter-list > variable-declaration

      (1). variable-declaration: 变量的声明,声明的变量名成为模版名;

      (2).parameter-list: 模版参数的非空逗号分隔列表,每个参数都是non-type parameter, a type parameter, a template parameter, or a parameter pack of any of those.

      从变量模版实例化的变量称为实例化变量。从静态数据成员模版实例化的静态数据成员称为实例化静态数据成员。

      以下为测试代码:

namespace {

// reference: https://en.cppreference.com/w/cpp/language/variable_template
template
constexpr T pi = T(3.1415926535897932385);  // variable template

template
T circular_area(T r) // function template
{
	return pi * r * r; // pi is a variable template instantiation
}

struct limits {
	template
	static const T min; // declaration of a static data member template
};

template
const T limits::min = { T(1.2) }; // definition of a static data member template

template
class X {
public:
	static T s; // declaration of a non-template static data member of a class template
};

template
T X::s = 1.2; // definition of a non-template data member of a class template

// reference: https://www.anycodings.com/1questions/4931124/c14-variable-templates-what-is-their-purpose-any-usage-example
template
const int square = N * N;

template
T n = T(5);

} // namespace

int test_variable_template()
{
	// 1. function template
	std::cout << "int value:" << circular_area(1) << "\n"; // int value:3
	std::cout << "float value:" << circular_area(1.f) << "\n"; // float value:3.14159

	// 2. static data member template
	std::cout << "int limits::min:" << limits::min << "\n"; // int limits::min:1
	std::cout << "float limits::min:" << limits::min << "\n"; // float limits::min:1.2

	std::cout << "int X::s:" << X::s << "\n"; // int X::s:1
	std::cout << "float X::s:" << X::s << "\n"; // float X::s:1.2

	// 3. compile time code
	std::cout << "square:" << square<5> << "\n"; // square:25

	// 4. it seems to instantiate the variables separately for the type
	n = 10;
	std::cout << "n:" << n << "\n"; // n:10
	std::cout << "n:" << n << "\n"; // n:5

	return 0;
}

      windows和linux执行结果如下图所示:

C++14中变量模版的使用_第1张图片

      GitHub: https://github.com/fengbingchun/Messy_Test

你可能感兴趣的:(c++14)