简体   繁体   English

CRTP层级类的非模板基类

[英]Non-template base class for CRTP hierarcy class

Consider the following class hierarchy with CRTP : 考虑以下带有CRTP的类层次结构:

template <class T> 
struct BaseClass {
    void foo_interface(int a) {
        static_cast<T*>(this)->foo(a);
    }
};

struct SubClass1 : public BaseClass<SubClass1> {
     void foo(int a) { std::cout << "SubClass1\n"; }
};

struct SubClass2 : public BaseClass<SubClass2> {
     void foo(int a) { std::cout << "SubClass2\n"; }
};

int main(int argc, char* argv[]) {

    BaseClass<SubClass1>* b1 = new SubClass1();
    BaseClass<SubClass2>* b2 = new SubClass2();

    b1->foo_interface(3); // Print "SubClass1"
    b2->foo_interface(4); // Print "SubClass2"

    delete b1;
    delete b2;
}

I need to create a SuperClass of BaseClass to obtain the same behaviour but in the following way (I have to iterate on a collections of object and call this method): 我需要创建一个BaseClass的超类来获得相同的行为,但是要采用以下方式(我必须遍历对象的集合并调用此方法):

int main(int argc, char* argv[]) {

    SuperClass* b1 = new SubClass1();
    SuperClass* b2 = new SubClass2();

    b1->foo_interface(3); // Print "SubClass1"
    b2->foo_interface(4); // Print "SubClass2"

    delete b1;
    delete b2;
}

It is possible? 有可能的? I can't use virtual methods and I try to avoid function pointers. 我不能使用虚拟方法,并且尝试避免使用函数指针。 The method foo_interface can be also defined outside from all classes. foo_interface方法也可以在所有类的外部定义。 These methods must be called a lot of times, thus i can't use switch/if constructs for performance reasons. 这些方法必须被调用很多次,因此出于性能原因,我不能使用switch / if构造。

You can't have a run-time interface without run-time dispatch (which you have banned). 没有运行时调度(您已禁止),就不能有运行时界面。 Therefore, it's impossible for you to do what you want. 因此,您不可能做自己想做的事情。 If you want a run-time interface, you need run-time dispatch through say function pointers or virtual functions. 如果需要运行时接口,则需要通过诸如函数指针或虚拟函数的运行时调度。

You could also consider putting the different subclasses in different collections. 您也可以考虑将不同的子类放入不同的集合中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM