c++ - 类型到 int 的映射

标签 c++ serialization c++11 traits

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

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

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

最佳答案

确保 uniqe 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> { };

关于c++ - 类型到 int 的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3741682/

相关文章:

c++ - 什么是 Trinity API

c++ - 托管可执行文件中的非托管库导致托管异常

java - 哪些类型的类不应该被序列化

c++ - 以非顺序顺序在 vector 中分配值

c++ - 如何使用 boost-range 在函数中封装自定义迭代器

c++ - 捕获屏幕的替代方法? (C++, Windows 操作系统)

c++ - 在 Linux 中为 c++ 使用 gprof -f 选项

python - 将 numpy 数组列表转换为 json 以从 flask api 返回

java - 匿名类上的 NotSerializableException

c++ - 反转链表,为什么 head 不应该指向原来的第一个元素?