[英]Create a templated struct or a map from Integer key to a variable type in C++
The problem I am facing is the following I have some data stored in an array of unknown type array
. 我面临的问题是以下我将一些数据存储在未知类型array
。 However there is function array_getDataType()
which given the array returns an integer for instance UBIT8
where UBIT8
is a constant defined somewhere and this basically means that the type of the elements stored in the array is unsigned char
. 但是有一个函数array_getDataType()
给定数组返回一个整数,例如UBIT8
,其中UBIT8
是在某处定义的常量,这基本上意味着存储在数组中的元素类型是unsigned char
。 I was wondering if there was some way to create a map between these defined constants and actual types, something that would take in "BIT8" and return "unsigned char". 我想知道是否有某种方法可以在这些定义的常量和实际类型之间创建映射,而这种映射将采用“ BIT8”并返回“ unsigned char”。 I know there is a way to do the opposite with templates in the following way. 我知道有一种方法可以通过以下方式对模板进行相反处理。
template< typename T >
struct type2Int
{
enum { id = 0 };
};
template<> struct type2Int<unsigned char> { enum { id = UBIT8 }; };
and this can later be used as 以后可以用作
type2Int<unsigned char> type;
then 然后
type.id
would be whatever is the definition of UBIT8
I was wondering how to do the opposite. UBIT8
的定义是什么,我想知道如何做相反的事情。
I was wondering how to do the opposite. 我不知道如何做相反。
In a similar way, using template specialization. 以类似的方式,使用模板特殊化。
By example 举个例子
#include <iostream>
template <std::size_t>
struct int2type;
// { using type = void; }; ???
template <>
struct int2type<0U>
{ using type = char; };
template <>
struct int2type<1U>
{ using type = int; };
template <>
struct int2type<2U>
{ using type = long; };
int main()
{
static_assert(std::is_same<typename int2type<0>::type, char>::value, "!");
static_assert(std::is_same<typename int2type<1>::type, int>::value, "!");
static_assert(std::is_same<typename int2type<2>::type, long>::value, "!");
}
If you can't use C++11 (so no using
), you can use the good-old typedef
如果您不能使用C ++ 11(所以没有using
),你可以使用好老typedef
template <std::size_t>
struct int2type;
template <>
struct int2type<0U>
{ typedef char type; };
// ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.