我有两个 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/