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

相关推荐
handler0121 分钟前
拒绝权限报错!三分钟掌握 Linux 权限管理
linux·c语言·c++·笔记·学习
拾贰_C25 分钟前
【Google | Gemini | API | POST】怎么使用Google 的Gemini API (原生版)
开发语言·lua
t***5441 小时前
如何在Dev-C++中选择Clang编译器
开发语言·c++
橙子199110161 小时前
Java 基础相关
java·开发语言
汉克老师2 小时前
GESP2023年9月认证C++三级( 第一部分选择题(9-15))
c++·gesp三级·gesp3级
星越华夏2 小时前
python——三角函数用法
开发语言·python
代码中介商2 小时前
C语言数据存储深度解析:从原码反码补码到浮点数存储
c语言·开发语言·内存
2501_933329555 小时前
企业级舆情监测系统技术解析:Infoseek数字公关AI中台架构与实践
开发语言·人工智能·自然语言处理·架构
Wave8455 小时前
C++继承详解
开发语言·c++·算法