【问题标题】:How to define a template specific type that can be inherited?如何定义可以继承的模板特定类型?
【发布时间】:2019-07-01 10:38:07
【问题描述】:

我的问题可能没有我想的那么清楚。 让我解释。 我有一个抽象的母班 M,还有很多子班 C1,C2,...Cn。 在每个孩子中,我必须像这样定义模板类型:

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 一起使用这种类型

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

我知道这是不可能的

error: invalid use of ‘this’ at top level

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

这可能吗?

【问题讨论】:

标签: c++ templates inheritance


【解决方案1】:

CRTP 可能会有所帮助:

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);
};

【讨论】:

  • @foreknownas_463035818:我在 CRTP 中保留了 Mother 继承。
  • 很抱歉忽略了这一点。这是一个常见的误解,我没有仔细阅读就惊慌失措
猜你喜欢
  • 2011-11-30
  • 2020-06-26
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
相关资源
最近更新 更多