Ale*_*zzi 6 c++ mapping templates template-meta-programming
我有一组与一对一关系相关的类型,例如:
TypeA ---> Type1
TypeB ---> Type2
TypeC ---> Type3
Run Code Online (Sandbox Code Playgroud)
我在编译时就知道这些关系.
然后,我有一个依赖于这两种类型的模板类:
template<class T1,class T2>
class MyClass
{
T1 foo;
T2 bar;
};
Run Code Online (Sandbox Code Playgroud)
现在,我的库的用户将键入以下内容:
MyClass<TypeA,Type1> x;
Run Code Online (Sandbox Code Playgroud)
这是不方便的,因为两种类型之间存在依赖关系,并且应该足以让用户仅指定第一种类型.
此外,不应该混合这两种类型:
MyClass<TypeA,Type2> y; //it should not compile
Run Code Online (Sandbox Code Playgroud)
我对模板元编程不是很熟悉,我觉得这是可行的任务,但我可能错了.
涉及的类型数量很大,但是我很乐意在必要时运行脚本来生成代码.
你知道是否有可能或者我在浪费时间吗?你有什么想法让我指出正确的方向吗?
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;
};
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)