类型到int映射 [英] type to int mapping

查看:49
本文介绍了类型到int映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 = ...; }; };

程序之间的

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

推荐答案

确保唯一ID的一种方法是滥用朋友功能定义

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

这篇关于类型到int映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆