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 :
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.