0

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.

1
  • What you are going to do after getting the data type? Commented Jun 9, 2017 at 13:00

1 Answer 1

1

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

template <std::size_t>
struct int2type;

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

// ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.