static polymorphism

Hey guys,

static polymorphism may look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Example program
#include <iostream>
#include <string>
#include <vector>
 
template<typename T> class Base {
public: 
    void  Run() { return static_cast<T*>(this)->DoIt(); }
};
 
class Derived1 : public Base<Derived1> {
public:
    void  DoIt() { std::cout << "d1" << std::endl;  }
};
 
class Derived2 : public Base<Derived2> {
public:
    void  DoIt() { std::cout << "d2" << std::endl;  }
};

The problem with this pattern is that I can't have a std::vector of Base-classes because Base is a class template, so I can only instanciate classes themselves, right?
1
2
3
4
5
6
7
int main() {
    Derived1 Obj1;
    Derived2 Obj2;
 
    Obj1.Run(); /* runs the actual DoIt() implementation */
    Obj2.Run(); /* runs the actual DoIt() implementation */
};

http://cpp.sh/8tjp

Now I have 2 questions:
1.) What difference is there to just name the function in Derived1 and Derived2 "Run" and have no base-class at all?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class NotDerived1 {
public:
    void  Run() { std::cout << "d1" << std::endl;  }
};
 
class NotDerived2 {
public:
    void  Run() { std::cout << "d2" << std::endl;  }
};
 
int main() {
    NotDerived1 Obj1;
    NotDerived2 Obj2;
 
    Obj1.Run(); /* runs the actual DoIt() implementation */
    Obj2.Run(); /* runs the actual DoIt() implementation */
};

http://cpp.sh/8ztxl

2.) When I want to store the Objects in a std::vector<Base*> I could make a non-template base class and a derive_helper<T> class.
The function run has to be virtual because Base does not know what type derives from it but I want to be able to call it on a Base-Object...
Now I have basically combined static and dynamic polymorphism.
Do I still get a better performance? (it wouldn't make sense to me)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Example program
#include <iostream>
#include <string>
#include <vector>

class Base {
public:
    virtual ~Base() {}
    virtual void run() = 0;
};
template <typename T>
class derive_helper : public Base {
public:
    virtual void run() final override { static_cast<T*>(this)->do_stuff(); }
};

class d1 : public derive_helper<d1> {
public:
    void do_stuff() { std::cout << "d1" << std::endl; }
};
class d2 : public derive_helper<d2> {
public:
    void do_stuff() { std::cout << "d2" << std::endl; }
};

int main()
{
    std::vector<Base*> bases;
    bases.push_back(new d1());
    bases.push_back(new d2());
    bases.push_back(new d1());
    
    for(auto& i : bases) {
        i->run();
        delete i;
    }
}

http://cpp.sh/43ah

I hope my questions are clear enough
Last edited on
Topic archived. No new replies allowed.