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对象

相关推荐
小陈工27 分钟前
2026年4月2日技术资讯洞察:数据库融合革命、端侧AI突破与脑机接口产业化
开发语言·前端·数据库·人工智能·python·安全
Zarek枫煜1 小时前
C3 编程语言 - 现代 C 的进化之选
c语言·开发语言·青少年编程·rust·游戏引擎
阿kun要赚马内1 小时前
Python中元组和列表差异:底层结构分析
开发语言·python
筱璦1 小时前
期货软件开发 - C# 调用 HQChart 指标计算 C++ 动态库
c++·microsoft·c#
不想写代码的星星2 小时前
C++ 内存管理:分区、自定义分配器、常见问题与检测工具
c++
前进的李工2 小时前
MySQL大小写规则与存储引擎详解
开发语言·数据库·sql·mysql·存储引擎
错把套路当深情2 小时前
Java 全方向开发技术栈指南
java·开发语言
前端郭德纲2 小时前
JavaScript Object.freeze() 详解
开发语言·javascript·ecmascript
-许平安-2 小时前
MCP项目笔记九(插件 bacio-quote)
c++·笔记·ai·plugin·mcp