c++元编程tookit类

前言

下面记录几个,在c++元编程中常用的工具类。

Hollow Types

instance_of

代码

c 复制代码
struct instance_of
{
	typedef T type;
	instance_of(int = 0)
	{
	}
};

const instance_of<int> I_INT = instance_of<int>(); // 这种写法有点繁琐
const instance_of<double> I_DOUBLE = 0; // 使用这种写法
// also fine.

作用

快速创建一个global对象,立刻初始化。

empty

代码

c 复制代码
struct empty
{
	empty() {}
};
// const empty EMPTY; 这种写法可能会报 unused的警告
const empty EMPTY = 0;

作用

用该类表示空。

Selector

代码

c 复制代码
template <bool PARAMETER>
struct selector
{
};
typedef selector<true> true_type1;
typedef selector<false> false_type;

作用

可以作为类型参数来做偏特化选择。

Static Value

代码

c 复制代码
template <typename T, T VALUE>
struct static_parameter
{
};
template <typename T, T VALUE>
struct static_value : static_parameter<T, VALUE>
{
	static const T value = VALUE;
	operator T () const
	{
	return VALUE;
	}
	static_value(int = 0)
	{
	}
};

//将static转为非static ,更安全
template <typename T, T VALUE>
inline T static_value_cast(static_value<T, VALUE>) //不需要用到形参,所以可以不用定义形参名
{
return VALUE;
};


int main() {
    auto a  =  static_value_cast(static_value<int, 3>());
    std::cout <<  a << "\n";
}

作用

快速创建一个static对象

相关推荐
2301_763472463 分钟前
C++20概念(Concepts)入门指南
开发语言·c++·算法
阿猿收手吧!19 分钟前
【C++】std::promise原理与实战解析
c++
TechWJ26 分钟前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
lly2024061 小时前
C++ 文件和流
开发语言
m0_706653231 小时前
分布式系统安全通信
开发语言·c++·算法
Zach_yuan1 小时前
深入浅出 JSONCpp
linux·服务器·网络·c++
寻寻觅觅☆1 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
lightqjx2 小时前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
zh_xuan2 小时前
kotlin lazy委托异常时执行流程
开发语言·kotlin
阿猿收手吧!2 小时前
【C++】string_view:高效字符串处理指南
开发语言·c++