Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 子类对象作为虚函数的参数_C++_Templates_Inheritance_Polymorphism_Virtual Functions - Fatal编程技术网

C++ 子类对象作为虚函数的参数

C++ 子类对象作为虚函数的参数,c++,templates,inheritance,polymorphism,virtual-functions,C++,Templates,Inheritance,Polymorphism,Virtual Functions,好的,基本上我在另一个类中使用了一个类,这个类要求对象报告它与同一类型的另一个对象的关系。效果很好。仅供参考该类代表一个协议。不幸的是,现在我试图通过添加一个名为包装器的类来修饰类关系。该类的主要功能是它可以将第一个类作为参数(或任何其他类似的参数): 我马上想到的一个解决方案是,将它从wrapperexplorer的接口中删除,只让编译器在与其他设计一起使用时抱怨缺少接口方法 所以我的问题是:有没有办法在抽象类的接口中放置一个方法,这样子类就必须将子类类型的对象作为参数 或者,我是否试图错误地

好的,基本上我在另一个类中使用了一个类,这个类要求对象报告它与同一类型的另一个对象的关系。效果很好。仅供参考该类代表一个协议。不幸的是,现在我试图通过添加一个名为包装器的类来修饰类关系。该类的主要功能是它可以将第一个类作为参数(或任何其他类似的参数):

我马上想到的一个解决方案是,将它从
wrapperexplorer
的接口中删除,只让编译器在与其他设计一起使用时抱怨缺少接口方法

所以我的问题是:有没有办法在抽象类的接口中放置一个方法,这样子类就必须将子类类型的对象作为参数


或者,我是否试图错误地使用继承?有人有任何有用的设计模式可以帮助我解决这个问题吗?

有一种叫做CRTP(奇怪的重复模板模式)的设计,它将子对象的类型作为模板参数传递给父对象:

template <typename Child>
class WrapperInterpreter {
    using Inner = typename Child::Inner; // nested typedef

    WrapperInterpreter(Inner const& ...);

    virtual bool respondsToMessage(Child const& ...) = 0;
};

template <typename Inner>
class Concrete: public WrapperInterpreter< Concrete<Inner> > {

    virtual bool respondsToMessage(Concrete const& ...) override;

};
模板
类包装器解释器{
使用Inner=typename子::Inner;//嵌套的typedef
包装器解释器(内部常量和…);
虚拟bool respondsToMessage(子常量&…)=0;
};
模板
类具体:公共包装解释器{
虚拟布尔响应消息(具体常量和…)覆盖;
};
template< class Inner >
class ConcreteWrapper : WrapperInterpreter<Inner>
{
    ...
    bool respondsToMessage(const ConcreteWrapper<Inner> &);
    ...
}
template <typename Child>
class WrapperInterpreter {
    using Inner = typename Child::Inner; // nested typedef

    WrapperInterpreter(Inner const& ...);

    virtual bool respondsToMessage(Child const& ...) = 0;
};

template <typename Inner>
class Concrete: public WrapperInterpreter< Concrete<Inner> > {

    virtual bool respondsToMessage(Concrete const& ...) override;

};