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.