【问题标题】:Multi inheritance with template interface带有模板接口的多继承
【发布时间】:2015-07-03 18:54:48
【问题描述】:

考虑以下代码:

模板.h

template<typename T>
class templ{
public:
    virtual const int virtualMethod(const T *const) const = 0;
}

Base.h

#include "template.h"

class Der1;
class Der2;

    class Base :
        public templ<Base>,
        public templ<Der1>,
        public templ<Der2>{
    public:
        virtual ~Base(){}
    };

Der1.h

#include "Base.h"

class Der1 : public Base {
public:
    virtual const int virtualMethod(const Base *const) const override;
    virtual const int virtualMethod(const Der1 *const) const override;
    virtual const int virtualMethod(const Der2 *const) const override;
};

Der1.cpp

#include "Der1.h"

const int Der1::virtualMethod(const Base *const sth) const{
    return sth->templ<Der1>::virtualMethod(this);//does not work
    //how to fix it?
}

const int Der1::virtualMethod(const Der1 *const sth) const{
    //do sth
}

const int Der1::virtualMethod(const Der2 *const sth) const{
    //do sth
}

Der2 类也继承自 Base 并实现了这三个功能。

对于这个代码编译器给了我这些信息:

  1. 'templ' is ambiguous ' 候选者是:templ() templ(const 模板 &) 模板 () 模板 (常量模板 &) 模板 () templ(const templ &) '
  2. 无法解析函数“virtualMethod”
  3. 命名空间成员函数“virtualMethod”无法解析。
  4. 类型“Der1”无法解析。
  5. 未定义的引用 `templ::virtualMethod(Der1 const*) const'

一般来说,代码的想法是实现双类型分派。虽然我认为我知道是什么导致了问题,但我不知道如何解决它。所以也许你可以帮助我。

【问题讨论】:

  • 您可能希望使用CRTP 而不是嵌入式抽象基类。
  • 请不要混合使用静态多态(模板)和动态多态(虚拟),除非您知道自己在做什么。
  • 另外,在定义接口时,应该使用虚拟继承(避免多个基类)
  • 你能发一个minimal, complete, and verifiable example吗?您的代码可以按原样编译,除非您缺少包含或其他内容。

标签: c++ templates multiple-inheritance


【解决方案1】:

我有点困惑你的意图是什么......

但是呢:

const int Der1::virtualMethod(const Base *sth) const { 
     return dynamic_cast<const templ<Der1> *>(sth)->virtualMethod(this);
}

【讨论】:

  • 这绝对是我所寻找的不是。我写代码的主要目的是避免dynamic_cast和RTTI。更不用说由于没有检查nullptr 的动态转换结果,您的代码很危险。
  • 当然,您应该检查演员阵容,但我忽略了这一点,因为这不是解决方案的主要部分,我认为在这种情况下不需要,因为演员阵容总是积极的(除非 sth = nullptr ,它也没有在您的代码中检查)。
猜你喜欢
  • 2013-03-31
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 2021-09-16
相关资源
最近更新 更多