如何定义可以继承的模板特定类型? [英] How to define a template specific type that can be inherited?

查看:121
本文介绍了如何定义可以继承的模板特定类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题可能不尽如人意. 让我解释. 我有一个抽象的母班M,还有很多子班C1,C2,... Cn. 在每个孩子中,我必须定义如下模板类型:

My question might not be as clear as I would like. Let me explain. I have an abstract mother class M, and a lot of child class C1,C2,...Cn. In each child, I have to define template types like this:

class Child1 : public Mother
{
    public:
    typedef AnotherTemplateClass<Child1,int>         Type1_C1;
    typedef AnotherTemplateClass<Child1,bool>        Type2_C1;
    typedef AnotherTemplateClass<Child1,unsigned>    Type3_C1;
    void DoSomething(Type1_C1 a, Type2_C1 b, Type3_C1);
};

我想定义以下内容:

class Mother
{    
    public:
    typedef AnotherTemplateClass<this,int>          Type1_M;
    typedef AnotherTemplateClass<this,bool>         Type2_M;
    typedef AnotherTemplateClass<this,unsigned>     Type3_M;
};

并使用此类型的Child1

and with Child1 using this type

class Child1 : public Mother
{
    void DoSomething(Type1_M a, Type2_M b, Type3_M c);
};

我知道不可能做到这一点

I know that is not possible to do that

error: invalid use of ‘this’ at top level

但是有什么语法可以解决这个问题吗?

but is there any syntax that could answer this problem?

那有可能吗?

推荐答案

CRTP可能有帮助:

CRTP might help:

template <typename Derived>
class ChildCrtp : public Mother
{
    public:
    typedef AnotherTemplateClass<Derived,int>         Type1_C1;
    typedef AnotherTemplateClass<Derived,bool>        Type2_C1;
    typedef AnotherTemplateClass<Derived,unsigned>    Type3_C1;

    Possibly:
    //void DoSomething(Type1_C1 a, Type2_C1 b, Type3_C1);
};

然后

class Child1 : public ChildCrtp<Child1>
{
public:
    void DoSomething(Type1_C1 a, Type2_C1 b, Type3_C1);
};

这篇关于如何定义可以继承的模板特定类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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