The problem I am facing is the following I have some data stored in an array of unknown type 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
. 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". 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.
答案 0 :(得分:1)
我想知道如何做相反的事情。
以类似的方式,使用模板专业化。
以示例
#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, "!");
}
如果你不能使用C ++ 11(所以没有using
),你可以使用古老的typedef
template <std::size_t>
struct int2type;
template <>
struct int2type<0U>
{ typedef char type; };
// ...