RedSkull
RedSkull

Reputation: 47

Same function for different classes being include in main C++

As you may have noticed from the title I have diverse classes specifically 3 and each one respond to a different tree implementation.

In Tree1.h

class Tree1 {
public:

    struct node{
        char label;
        node* nHMI_ptr;
        node* nHD_ptr;
    };

    node* root;

    Tree1();

    ~Tree1();    

    bool Empty();

    Tree1::node& Root();

    void AddSon(int i, node &n, char l);
    /*
     *
     * (other functions)
     */
}

In Tree2.h

class Tree2 {
public:

    struct node{
        char label;
        node* nHMI_ptr;
        node* nHD_ptr;
        node* nFather_ptr;
        node* nHI_ptr;
    };

    node* root;

    Tree2();

    ~Tree2();

    bool Empty();

    Tree2::node& Root();

    void AddSon(int i, node &n, char l);
    /*
     *
     * (other functions)
     */
}

In Tree3.h

class Tree3{
public:
    Tree3();

    ~Tree3();

    struct node;

    struct nodeSon{
        struct node* node_ptr;
        nodeSon* nextNodeSon_ptr;
    };

    struct node{
        char label;
        node* nextNode_ptr;
        struct nodeSon* nSon;
    };

    node* root;

    bool Empty();

    Tree3::node& Root();

    void AddSon(int i, node &n, char l);
    /*
     *
     * (other functions)
     */
}

As you can see they have functions and members under the same name or identifier. This is because I want to make various more complex algorithms using this functions but the tricky part is that I want to make this algortihms independent of the class being used. The first thing that came to my mind was to create this algorithms on my main.cpp.

In main.cpp

#include <cstdlib>
#include <iostream>
#include "Tree1.h"
//#include "Tree2.h"
//#include "Tree3.h"

void someFunc(node n) {
    //do something by calling Tree functions
    //E.g. call Empty(), call AddSon(...)
}

int main(int argc, char** argv) {
    return 0;
}

What I am trying to achive is that someFunc(...) works on all of the trees without changing any of the underlying code and just by enabiling one of the #include and disabling the other two.

Upvotes: 1

Views: 108

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

  • Is it possible to do it?

Yes

  • How can I accomplish this?

You simply can provide a template function:

template<class TreeType>
void someFunc(TreeType& treeContext, typename TreeType::node& n) {
    //do something by calling Tree functions
    //E.g. call Empty(), call AddSon(...)
}

Upvotes: 3

Related Questions