C++变量模板(variable template)

template用在一个变量上,其目的是什么呢?
https://blog.csdn.net/zwvista/article/details/54612025

#include <iostream>
#include <iomanip>
using namespace std;

// 函数模板
template<class T>
constexpr T pi_fn()
{
	return T(3.1415926535897932385);
}
// 变量模板
template<class T>
constexpr T pi = T(3.1415926535897932385);


int main()
{
	cout << pi_fn<int>() << pi<int> << '\n'; // 33
	cout << setprecision(10) << pi<float> << '\n'; // 3.141592741
	cout << setprecision(10) << pi<double> << '\n'; // 3.141592654
	return 0;
}

假设我们需要一个能转成一定数值类型的圆周率。
如果数值类型为int,圆周率pi就是int(pi)=3。
如果数值类型为float,圆周率pi就是float(pi)=3.1415927。
如果数值类型为double,圆周率pi就是double(pi)=3.141592653589793。
在C++14之前,这样的常量只能被定义为函数模板。
在C++14之后,我们可以用变量模板直接定义这样的常量

https://skypjack.github.io/2020-03-14-ecs-baf-part-8/
中提到,为不同类型创建一个唯一的标识。

class generator {
    inline static std::size_t counter{};

public:
    template<typename Type>
    inline static const std::size_t type = counter++;
};
使用:
const auto type = generator::type<my_class>;

the basic idea is quite simple.
we have a shared counter that is incremented every time we generate an identifier for a new type.
since type is a vriable template, it forces an increment of counter with every specialization.

in case type has been already initialized, its value is returned without affecting counter anymore.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值