type to int mapping

Tho*_*mas 5 c++ serialization traits c++11

我有两个c ++程序需要有一个type -> int在编译时已知并且在两个程序之间相同的映射.此外,我想在编译时自动确保地图是一对一的.你会如何解决这个问题?(允许使用c ++ 0x扩展名).第一部分很简单:分享一个

template < typename T > struct map;
template <> struct map <...> { enum { val = ...; }; };
Run Code Online (Sandbox Code Playgroud)

程序之间.(第二部分意味着我不想val在我的程序中的某个地方意外地为两种不同类型定义相同的内容.)

Joh*_*itb 9

确保uni ide id的一种方法是滥用友元函数定义

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> { };
Run Code Online (Sandbox Code Playgroud)