A problem passing functions from std as a function parameter

I’m trying to figure out how to pass an std function as a parameter. Here is a brief example: #include <cmath> #include <functional> #include <iostream> void bar(const double v, std::function<int(int)> foo) { std::cout << foo(v) << std::endl; } int main() { bar(-23., std::abs); } This code fails to compile with a message no matching function… Read More A problem passing functions from std as a function parameter

Why and how is std::function<void()> allowed to be assigned to callables with return types in C++?

The following code is legal C++: int m() { return 42; } int main() { std::function<void()> func, func2; func = m; func2 = [&]() -> std::string { return "This does not return void"; }; } By passing void() to std::function‘s template argument list, I assumed that meant func and func2 must be assigned to functions/lambdas… Read More Why and how is std::function<void()> allowed to be assigned to callables with return types in C++?

What exactly is std::function<void(int)> doing in this code?

I’ve recently come across some code for the inorder traversal of a binary search tree which is as follows: void binary_search_tree::inorder_traversal(bst_node *node, std::function<void(int)> callback) { if (node == nullptr) { return; } inorder_traversal(node->left, callback); callback(node->value); inorder_traversal(node->right, callback); } std::vector<int> binary_search_tree::get_elements_inorder() { std::vector<int> elements; inorder_traversal(root, [&](int node_value) { elements.push_back(node_value); }); return elements; } From my understanding,… Read More What exactly is std::function<void(int)> doing in this code?