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

相关推荐
Never_Satisfied14 小时前
在JavaScript / HTML中,数组查找第一个符合要求元素
开发语言·javascript·html
嵌入式×边缘AI:打怪升级日志14 小时前
9.2.1 分析 Write File Record 功能(保姆级讲解)
java·开发语言·网络
橙露14 小时前
Python 异步爬虫进阶:协程 + 代理池高效爬取实战
开发语言·爬虫·python
肆忆_14 小时前
Day 02|控制块分离架构:Boost 风格 shared_ptr 骨架落地
c++
kylezhao201915 小时前
C#异步和并发在IO密集场景的典型应用 async/await
开发语言·数据库·c#
m0_5312371715 小时前
C语言-函数练习2
c语言·开发语言
锅包一切15 小时前
在蓝桥杯边练边学Rust:2.原生类型
开发语言·学习·蓝桥杯·rust
lightqjx15 小时前
【C++】C++11 常见特性
开发语言·c++·c++11
一切尽在,你来15 小时前
AI 大模型应用开发前置知识:Python 泛型编程全教程
开发语言·人工智能·python·ai编程
shix .15 小时前
旅行网站控制台检测
开发语言·前端·javascript