8

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

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

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

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

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

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

MyClass<TypeA,Type1> x;

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

此外,不应该混合这两种类型:

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

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

所涉及的类型数量很多,但是如果需要,我很乐意运行脚本来生成代码。

你知道这是可能的还是我在浪费时间?您有什么想法可以为我指明正确的方向吗?

4

3 回答 3

8
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;
};
于 2011-10-12T12:16:59.107 回答
5
template<class T> struct TypeLetter2TypeDigit;

template<> struct TypeLetter2TypeDigit<TypeA> { typedef Type1 type; };
template<> struct TypeLetter2TypeDigit<TypeB> { typedef Type2 type; };
template<> struct TypeLetter2TypeDigit<TypeC> { typedef Type3 type; };


template<class T1>  // Type2 is not needed
class MyClass 
{ 
  // Type2 is deduced.
  typedef typename TypeLetter2TypeDigit<T1>::type T2;
  T1 foo; 
  T2 bar; 
}; 
于 2011-10-12T12:16:13.943 回答
3

为什么不只创建一个包装器类型:

template <typename T1, typename T2>
struct wrapper
{
   typedef T1 type1;
   typedef T2 type2;
};

typedef wrapper<TypeA, Type1> TypeX;
typedef wrapper<TypeB, Type2> TypeY;
typedef wrapper<TypeC, Type3> TypeZ;

然后用户说,,MyClass<TypeX>;你定义:

template <typename T>
class MyClass
{
  typename T::type1 foo;
  typename T::type2 bar;
};

如果要防止滥用模板,请使用部分特化:

template <typename> class MyClass; // undefined

template <typename S, typename T>
class MyClass<wrapper<S,T>>
{
  S foo;
  T bar;
};

这种方法可以很容易地扩展以将更多的编译时数据包含到包装类中。或者,您可以使用std::pair成员类型first_typesecond_type不是。

于 2011-10-12T12:15:27.077 回答