Lightsong
Lightsong

Reputation: 345

How to refer to private variables as arguments in auxiliary functions in a generic template

I am doing a project using generic templates in C++ in modular programming (we don't use OOP concepts)

We are having an issue understanding how to refer in an auxiliary function to a single variable in the template, which is a struct itself, without referring to the whole struct.

To put an example, because it sounds weird, we have:

template<typename T>
struct tree {
    friend void addElement<T> (tree<T>& c, const T& e);
    struct Node {
        T element; // template element
        Nodo* left;
        Nodo* right;
    };
 
    Node* root;
    int size;

}

template<typename T>
void friend void addElement<T> (tree<T>& c, const T& e);
    insert(c.root, e);
    c.size++;
}

// auxiliary function
template<typename T>
void insert(tree<T>root node, const T& e) { 
// how to refer to taking a Node* as an argument? we want 
// to modify the node structure of the tree in a recursive way, 
// so we will need to pass Node->left or Node->right as arguments
    // code 
}

We have tried multiple ways of doing this, none worked so far. How could this be done?

Thanks!

Upvotes: 0

Views: 111

Answers (1)

Jarod42
Jarod42

Reputation: 217880

Syntax would be tree<T>::Node* node and as it is a dependent name, we have to use extra typename: typename tree<T>::Node* node:

template<typename T>
void insert(typename tree<T>::Node* node, const T& e) { 
     // ...
}


template<typename T>
void addElement(tree<T>& c, const T& e)
{
    insert(c.root, e);
    c.size++;
}

Demo.

You probably want to pass that pointer by reference though.

Upvotes: 1

Related Questions