Type mapping in int

I have two C ++ programs that must have a map type -> intthat is known at compile time and is equal between two programs. In addition, I would like to automatically make sure that during compilation the map will be one-to-one. How would you decide that? (C ++ 0x extensions are allowed). The first part is simple: share

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

between programs. (The second part means that I don’t want to accidentally define the same valfor two different types somewhere in my programs.)

+5
source share
4 answers

One way to provide uniqe authentication is to use friend function descriptions

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> { };
+9

boost:: mpl:: map? - :

// Include your headers

using namespace boost::mpl;
typedef map<
      pair<1,MyFirstClass>
    , pair<2,MySecondClass>
    , pair<3,MyThirdClass>
    > m;
+2

, :

template<class T>
int generate_type_id() {

    static int value = 0;
    return value++;

}

template<class T>
int type_id() {

    static int value = generate_type_id<T>();
    return value;

}

, , :

type_id<int>();
type_id<Foo>();
type_id< map<string, pair<int, Bar> >();

, , , #include , , . , , , . .

+1

.

.

, , , ++.

0
source

All Articles