Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are members of a struct also a type?

The code below is from <The c++ template the complete guide> I don’t know why it works, is left and right a type here too?

// define binary tree structure and traverse helpers:
struct Node {
    int value;
    Node* left;
    Node* right;
    Node(int i=0) : value(i), left(nullptr), right(nullptr) {
}
…
};

    auto left = &Node::left;
    auto right = &Node::right;
    // traverse tree, using fold expression:
    template<typename T, typename… TP>
    Node* traverse (T np, TP… paths) {
    return (np ->* … ->* paths); // np ->* paths1 ->* paths2 …
}

int main()
{
    // init binary tree structure:
    Node* root = new Node{0};
    root->left = new Node{1};
    root->left->right = new Node{2};
    …
    // traverse binary tree:
    Node* node = traverse(root, left, right);
    …
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Probably you’re asking about the left and right defined at

auto left = &Node::left;
auto right = &Node::right;

These are not types; they are "pointer to member" variables. Here variable left represents the member left of struct Node, in a way that we can take any Node and the value of pointer to member left and find the member object left, using the .* or ->* operators which are specifically for pointer-to-members.

Specifically, each has the type "pointer to Node* member of Node". Without using auto, those two lines would be

Node* Node::*left = &Node::left;
Node* Node::*right = &Node::right;

… so thank goodness for auto.

When these pointer-to-member variables are passed to traverse, the template parameter pack TP is deduced as two of the same type Node* (Node::*). Finally, the fold expression applies the ->* to get the specified members, in sequence, going through the tree.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading