Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type to int mapping

I have two c++ programs that need to have a map type -> int that is known at compile time and equal between the two programs. Furthermore, I'd like to automatically make sure at compile time that the map is one-to-one. How would you solve that? (c++0x-extensions are allowed). The first part is easy: Share a

template < typename T > struct map;
template <> struct map <...> { enum { val = ...; }; };

between the programs. (The second part means that I don't want to accidently define the same val for two different types somewhere in my programs.)

like image 270
Thomas Avatar asked Sep 18 '10 12:09

Thomas


1 Answers

One way to ensure uniqe ids is to abuse friend function definitions

template<int N>
struct marker_id {
  static int const value = N;
};

template<typename T>
struct marker_type { typedef T type; };

template<typename T, int N>
struct register_id : marker_id<N>, marker_type<T> {
private:
  friend marker_type<T> marked_id(marker_id<N>) {
    return marker_type<T>();
  }
};

template<typename T>
struct map;

template<>
struct map<int> : register_id<int, 0> { };

// The following results in the following GCC error
// x.cpp: In instantiation of 'register_id<float, 0>':
// x.cpp:26:43:   instantiated from here
// x.cpp:14:29: error: new declaration 'marker_type<float> marked_id(marker_id<0>)'
// x.cpp:14:29: error: ambiguates old declaration 'marker_type<int> marked_id(marker_id<0>)'
//
//// template<>
//// struct map<float> : register_id<float, 0> { };
like image 137
Johannes Schaub - litb Avatar answered Sep 28 '22 19:09

Johannes Schaub - litb