About template programming !

First to say, I am making a game.
I need all objects to have intrusive lists with 1 global process, so that I call first object, and then each next performs it, until the process comes to the first object again. But the process is special for different objects of course.
I heard, template programming is cool, so I wanna use it, but I am not sure how.
The question is about how to make this process global and special, benefitting from template programming efficience.

Here is my try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Link {
private:
    Link * prev;
    Link * next;

public:
//...some possible stuff
    virtual void globalProcess() = 0;
};

template <class T>
class Common : public Link {
public:
    void globalProcess() {
        static_cast<T*>(this)->specialProcess();
    }
};

class Child : public Common<Child> {
    void specialProcess() {
    }
};


Is it even close to how it should be?
Last edited on
I heard, template programming is cool, so I wanna use it, but I am not sure how.


Template programming might be "cool", but that doesn't necessarily make it the right tool for this job.


It sounds like you just want a sort of 'master list' to house a bunch of objects? This sounds to me like you just want plain old polymorphism with your objects housed in a vector/list.

Maybe something like this:
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
38
39
40
41
42
43
44
45
46
47
48
49
50
class Object
{
public:
    static std::vector<std::unique_ptr<Object>>     objectList;

    virtual ~Object() {}

    virtual void someProcess() = 0;

    static void callAllProcesses()
    {
        for(auto& i : objectList)
            i->someProcess();
    }
};

class ChildA : public Object
{
public:
    virtual void someProcess() override
    {
        // do a thing specific to ChildA
    }
};

class ChildB : public Object
{
public:
    virtual void someProcess() override
    {
        // do a thing specific to ChildB
    }
};

///////////////////////////////////////////
#include <vector>
#include <memory>

std::vector<std::unique_ptr<Object>> Object::objectList;

int main()
{
    // create some objects, and add them to the main object list
    Object::objectList.emplace_back( new ChildA() ); // <- add a ChildA object
    Object::objectList.emplace_back( new ChildB() ); // <- add a ChildB object
    Object::objectList.emplace_back( new ChildA() ); // <- add another ChildA object
    
    // Then call each of those object's 'someProcess' function:
    Object::callAllProcesses();
}
Topic archived. No new replies allowed.