c++ - 如何从 Int2Type 构建 Type2Int?

标签 c++ templates

我有 Int2Type 特化

struct A; 
struct B;
template<int i> Int2Type;
template<> Int2Type<1> { typedef A type; }; 
template<> Int2Type<2> { typedef B type; };

我可以自动构建反向 Type2Int 特化吗? Type2Int<A>::value==1等等

谢谢

PS当然可以定义宏

#define I2T(i, T) template<> Int2Type<i> { typedef T type; }; template<> Type2Int<T> { static const int value = i; }; 

但我不想更改现有代码,可能以其他方式存在...

更新

A、B等人住在不同的文件里

common.h
template<int i> Int2Type;

a.h
struct A;     
template<> Int2Type<1> { typedef A type; }; 

b.h
struct B;    
template<> Int2Type<2> { typedef B type; };

我需要两个编译时“映射”- type by int 和 int by type;

Int2Type<1>::type a;
someFunc(Type2Int<A>::value)   

最佳答案

直接?不,这样的事情在 C++ 中是不可能的。但是,有了中间类型,我们可以通过几个助手自己实现这样的事情。

如果没有 C++11,请查看 Boost.MPL图书馆。具体来说,我们想要 boost::mpl::vector :

typedef boost::mpl::vector<A, B> IndexedTypes;

template <int I>
struct Int2Type {
    typedef typename boost::mpl::at<IndexedTypes, 
                 boost::mpl::int_<I - 1>
                 >::type type;
};

template <typename T>
struct Type2Int {
    typedef typename boost::mpl::begin<IndexedTypes>::type begin;
    typedef typename boost::mpl::find<IndexedTypes, T>::type iter;

    static const int value = boost::mpl::distance<begin, iter>::type::value + 1;
};

那应该给你 Int2Type<1>::type作为A , 和 Type2Int<B>作为2 .

使用 C++11,我们可以将这些写成基于可变序列的短元函数:

template <typename...> struct sequence { };
using IndexedTypes = sequence<A, B>;

关于c++ - 如何从 Int2Type 构建 Type2Int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29518736/

相关文章:

c++ - Cocoa-track 的菜单/将选项注入(inject) itunes

c++ - 扫描快速排序拆分

c++ - 获得所需的最少射门次数,以便进球数超过射门数是给定的百分比

C++ 模板 : return value by type

c++ - 构造函数和赋值运算符

c++ 检查 TCP 窗口是否已满?

c++ - GDB:在头文件中的模板类函数中设置断点时出错

C++ Vector Template Per-Component 操作

c++ - C++ 中 <type*[n]> 和 <type(*)[n]> 的区别

c++ - std::is_invocable 的奇怪行为