【类型元组序列化】(模板元编程 | 类型提取 | 类型映射 )

试想需要实现这样的功能:

type_list = { int, char, long, int * } 一个序列化的类型元组

type_list[2] var = 5L; ------(insignt : long var { 5L } ) 索引操作

或者

size_t index = find( type_list, int ) -----( insight : type_list[ index == 0 ] = int; ) 检索操作

接口规范如下:

using types =
type_sequence< int,
			   long,
			   char,
			   int *,
			   unsigned,
			   short >;
			   
constexpr
std::size_t length { types::size };

 测试代码如下:

template 
void index_mapping_to_type(std::index_sequence){
	int counter {};
    ((std::cout << "type_list[" << ++counter << "]: "
				<< typeid( get_type< Indices, types >).name()
				<< '\n' ), ...);
    std::cout << std::endl;
}

void type_mapping_to_index( void ){
	puts("index of unsigned");
	std::cout << get_index< unsigned, types >() << '\n';
	puts("index of int *");
	std::cout << get_index< int *, types >() << '\n';
}

int main( void ){
	index_mapping_to_type( std::make_index_sequence< length >() );
	puts("--------------");
	type_mapping_to_index();
	return 0;
}

 输出如下:

【类型元组序列化】(模板元编程 | 类型提取 | 类型映射 )_第1张图片

 具体实现

template < typename...Ts >
struct type_sequence{
	using type_pack = std::tuple< Ts... >;
	template < std::size_t I >
	using IType = std::tuple_element< I, type_pack >;
	static constexpr
	std::size_t size = sizeof...( Ts );
};

template < typename T, typename TYPE_SEQUENCE >
struct index;

template < typename T, typename...Ts >
struct index< T, type_sequence >{
	static constexpr std::size_t value = 0;
};

template < typename T, typename U, typename...Ts >
struct index < T, type_sequence< U, Ts... > >{
	static constexpr std::size_t value =
		index< T, type_sequence< Ts... > >::value + 1;
};

检索 type->maping->index

template < typename T, typename TYPE_SEQUENCE >
constexpr std::size_t
get_index( void ){
	return index< T, TYPE_SEQUENCE >::value;
}

索引 index->mapping->type

 

template < std::size_t I, typename TYPE_SEQUENCE >
using get_type =
typename std::decay_t< typename TYPE_SEQUENCE::template IType< I > >::type;

你可能感兴趣的:(语言特性,Modern,Cpp,设计模式,windows,算法,数据结构,stl,c++,模板方法模式)