@sehe Sorry, I forgot. The link is added to the post. theboostcpplibraries.com/boost.function – John 37 mins ago
Thanks for the added link.
Though I have his book in print and value his contributions to Boost introductory materials, I stand by my assessment that the wording here is unnecessarily confusing, and even misguiding: it seems to completely miss the fact that non-function callables can be assigned. This, IMO, is the whole point of doing the type erasure.
If you just wanted to define function pointers easily, you could just use function pointers:
static int my_function(const char*) { return 42; }
// regular function pointer stuff
{
using MyFunction = int(const char*);
MyFunction* pf = &my_function;
if (pf) {
std::cout << "pf(): " << pf(argument) << "\n";
}
}
But with boost::function (or std::function) you can also do:
// gereralized assignable callables:
boost::function<int(const char*)> f = &my_function;
if (f) {
std::cout << "same with f(): " << f(argument) << "\n";
}
struct MyCallable {
int operator()(const char*) const { return _retval; }
int _retval = 42;
};
f = MyCallable{};
std::cout << f(argument) << "\n"; // prints 42
f = MyCallable{99};
std::cout << f(argument) << "\n"; // prints 99
MyCallable instance { 10 };
f = std::ref(instance);
while (instance._retval--)
std::cout << f(argument) << "\n"; // prints 9 .. 0
LIVE DEMO
Live On Coliru
#include <boost/function.hpp>
#include <iostream>
static int my_function(const char*) { return 42; }
int main() {
auto argument = "dummy";
// regular function pointer stuff
{
using MyFunction = int(const char*);
MyFunction* pf = &my_function;
if (pf) {
std::cout << "pf(): " << pf(argument) << "\n";
}
}
// gereralized assignable callables:
boost::function<int(const char*)> f = &my_function;
if (f) {
std::cout << "same with f(): " << f(argument) << "\n";
}
struct MyCallable {
int operator()(const char*) const { return _retval; }
int _retval = 42;
};
f = MyCallable{};
std::cout << f(argument) << "\n"; // prints 42
f = MyCallable{99};
std::cout << f(argument) << "\n"; // prints 99
MyCallable instance { 10 };
f = std::ref(instance);
while (instance._retval--)
std::cout << f(argument) << "\n"; // prints 9 .. 0
}
Prints
pf(): 42
same with f(): 42
42
99
9
8
7
6
5
4
3
2
1
0