原文
注册器实现
示例代码
#pragma once
#include <type_traits>
#include <iostream>
template<typename _Type>
struct odr{inline static auto use = []{ //[1]std::cout << __PRETTY_FUNCTION__ << std::endl;//在这里利用宏,注册(类名,T)return 0;}();
};
template<typename _Type> //[2]
using crtp = decltype([]{odr<_Type>::use;}, odr<_Type>{});
原理
强制
编译器在主
前执行__PRETTY_FUNCTION__
符号输出,需要构造一组被动求值链
.
1,要求得crtp<_Type>
的类型,需求得推导类型
中的式类型
.
2,该式类型
依赖λ[2]
的类型,这是因为可重载,
3,静态成员变量use
的odr use
,依赖λ[1]
的执行结果
因此crtp<_Type>
的推导类型
的结果依赖
实例化λ[1]
.
使用注册器
#include "register.h"
struct foo final : crtp<foo>{};
struct bar final : crtp<bar>{};