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