在编译时映射两种类型 [英] Map two types at compile time

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

问题描述

我有一组与一对一关系相关的类型,例如:

I have a set of types related with a one-to-one relation, for example:

TypeA ---> Type1
TypeB ---> Type2 
TypeC ---> Type3

我在编译时就知道这些关系.

I know these relation at compile time.

然后,我有一个依赖于这两种类型的模板类:

Then, I have a template class that depends on this two types:

template<class T1,class T2>
class MyClass
{
  T1 foo;
  T2 bar;
};

现在,我的图书馆的用户将输入如下内容:

Now, the user of my library will type something like:

MyClass<TypeA,Type1> x;

这很不方便,因为两种类型之间存在依赖关系,对于用户仅指定第一种类型就足够了.

This is inconvenient because there is a dependency between the two types and it should be enough for the user specify only the first type.

而且,不可能将两种类型混合使用:

Also, mixing the two types shouldn't be possible:

MyClass<TypeA,Type2> y; //it should not compile

我对模板元编程不是很熟悉,给人的印象是这是可行的任务,但我可能是错的.

I am not very familiar with template meta programming, I got the impression that this is doable task, but I may be wrong.

涉及的类型数量很多,但是我很高兴在需要时运行脚本来生成代码.

The number of types involved is big, however I am happy to run a script to generate the code if necessary.

您知道是否有可能或者我在浪费时间?您有什么主意指向我正确的方向吗?

Do you know if it is possible or I am wasting my time? Do you have any ideas to point me on the right direction?

推荐答案

template<class T>
struct get_mapped;

template<>
struct get_mapped<TypeA>{
    typedef Type1 type;
};

// and so on....


template<class T>
class MyClass{
    typedef typename get_mapped<T>::type T2;

    T foo;
    T2 bar;
};

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

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