首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Variable template

变量模板定义了一系列变量或静态数据成员。

句法

template < parameter-list > variable-declaration

?

?

解释

variable-declaration

-

a declaration of a variable. The declared variable name becomes a template name.

parameter-list

-

a non-empty comma-separated list of the template parameters, each of which is either non-type parameter, a type parameter, a template parameter, or a parameter pack of any of those.

变量模板可以由名称空间范围的模板声明引入,其中声明声明变量。

二次

代码语言:javascript
复制
template<class T>
constexpr T pi = T(3.1415926535897932385);  // variable template
 
template<class T>
T circular_area(T r) // function template
{
    return pi<T> * r * r; // pi<T> is a variable template instantiation
}

二次

当在类作用域中使用时,变量模板声明静态数据成员模板。

二次

代码语言:javascript
复制
using namespace std::literals;
struct matrix_constants
{
    template<class T>
    using pauli = hermitian_matrix<T, 2>; // alias template
 
    template<class T> // static data member template
    static constexpr pauli<T> sigma1 = { { 0, 1 }, { 1, 0 } }; 
 
    template<class T>
    static constexpr pauli<T> sigma2 = { { 0, -1i }, { 1i, 0 } };
 
    template<class T>
    static constexpr pauli<T> sigma3 = { { 1, 0 }, { 0, -1 } };
};

二次

和其他人一样静态构件,可能需要静态数据成员模板的定义。此类定义是在类定义之外提供的。在命名空间范围内静态数据成员的模板声明也可以是非模板的定义。类模板的数据成员*

二次

代码语言:javascript
复制
struct limits {
    template<typename T>
    static const T min; // declaration of a static data member template
};
template<typename T>
const T limits::min = { }; // definition of a static data member template
 
template<class T>
class X {
   static T s; // declaration of a non-template static data member of a class template
};
template<class T>
T X<T>::s = 0; // definition of a non-template data member of a class template

二次

除非变量模板是显式专业化或者显式实例化时,当使用变量模板的专门化时,它将被隐式实例化。

变量模板的默认模板参数在需要参数值的上下文中使用变量模板时隐式实例化。

注记

在C++14中引入变量模板之前,参数化变量通常被实现为类模板的静态数据成员或作为返回所需值的参数函数模板。

变量模板不能用作模板模板参数...

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com