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

C++ Lambda Local Variable Capturing Error

I am trying to use a lambda expression to make inorderTraversal function reusable, and I am having the following error while trying to capture the local parameters of printStandartDeviation function: No viable conversion from ‘(lambda at […]/AVLTree.cpp:[…])’ to ‘void (*)(AVLTree::TreeNode *)’.

void AVLTree::printStandartDeviation() {
    int totalWordCount = 0, totalWordFrequencies = 0;
    inorderTraversal(root, [&totalWordCount, &totalWordFrequencies](TreeNode *tNode) {
        totalWordCount++;
        totalWordFrequencies += tNode->frequency;
    });
}

void AVLTree::inorderTraversal(TreeNode *tNode, void (*visit)(TreeNode *)) {
    if (tNode == nullptr) {
        return;
    } else {
        inorderTraversal(tNode->left, visit);
        visit(tNode);
        inorderTraversal(tNode->right, visit);
    }
}

It fixes if I make my local variables static or make them global, but I do not want to do either actually.

I am also open to alternative solutions as well instead of using lambda.

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

I would be grateful if you can help.

>Solution :

A lambda is not a function pointer. A non-capturing lambda has a conversion to function pointer but one with captures not. It is somewhat similar to the difference between a pointer to free function and pointer to member function where the pointer to member function alone is of little use. You need an object to call a member function. Here you also need the data, the captured variables, to call the lambda, its not just a function.

You do not need a function pointer. Simply pass the lambda as it is, and because the lambdas type has no name, make the method a template to make this work:

template <typename F>
void AVLTree::inorderTraversal(TreeNode *tNode, F&& visit) {
    // all the same
}
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