Reputation: 514
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.
Upvotes: 0
Views: 85
Reputation: 66200
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; };
// ...
Upvotes: 1