Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中创建一个模板结构或从整数键到变量类型的映射+;_C++_Templates_Types_Maps - Fatal编程技术网

C++ 在C+中创建一个模板结构或从整数键到变量类型的映射+;

C++ 在C+中创建一个模板结构或从整数键到变量类型的映射+;,c++,templates,types,maps,C++,Templates,Types,Maps,我面临的问题是,我有一些数据存储在未知类型的数组中array。然而,有一个函数array\u getDataType()给定数组返回一个整数,例如UBIT8,其中UBIT8是某个地方定义的常量,这基本上意味着数组中存储的元素类型是无符号字符。我想知道是否有某种方法可以在这些定义的常量和实际类型之间创建一个映射,这种映射将接受“BIT8”并返回“unsigned char”。我知道有一种方法可以通过以下方式使用模板实现相反的效果 template< typename T > struc

我面临的问题是,我有一些数据存储在未知类型的数组中
array
。然而,有一个函数
array\u getDataType()
给定数组返回一个整数,例如
UBIT8
,其中
UBIT8
是某个地方定义的常量,这基本上意味着数组中存储的元素类型是
无符号字符
。我想知道是否有某种方法可以在这些定义的常量和实际类型之间创建一个映射,这种映射将接受“BIT8”并返回“unsigned char”。我知道有一种方法可以通过以下方式使用模板实现相反的效果

template< typename T >
struct type2Int
{
     enum { id = 0 }; 
};
template<> struct type2Int<unsigned char>  { enum { id = UBIT8 }; };
无论UBIT8的定义是什么,我想知道如何做相反的事情

我想知道如何做相反的事情

以类似的方式,使用模板专门化

以身作则

#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, "!");
 }

获取数据类型后,您将执行什么操作?
type.id 
#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, "!");
 }
template <std::size_t>
struct int2type;

template <>
struct int2type<0U>
 { typedef char type; };

// ...