From the boost::bind docs( http://www.boost.org/doc/libs/1_53_0/libs/bind/bind.html#with_functions ), "The arguments that bind takes are copied and held internally by the returned function object", but if there's a way I could get the arguments copied in those function object?
i.e.:
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <string>
using namespace std;
void doSomthing(std::string str)
{
}
int main()
{
boost::function<void(void)> func_obj = boost::bind(&doSomthing, "some string");
//how can I get the std::string argument("some string") through func_obj?
}
thanks in advance.
There's not really much you can do with a Boost.Function object, except call it - and that's by design. (You can copy it, destroy it, compare to NULL, but not much more).
Consider the following code:
void Foo () {}
void Bar ( int i ) { printf ( "%d", i ); }
boost::function<void(void)> fFoo (Foo);
boost::function<void(void)> fBar = boost::bind (Bar, 23);
These two objects are designed to be treated identically. They are the same type, and behave the same. There's no mechanism in boost function for distinguishing between them.
For a great description of the techniques used in Boost.Function (and other places), check out Nevin Liber's type erasure talk from Boostcon 2010
Related
Shown below is a working code. But I want to use "this" keyword to call my function pointers inside my implementation (e.g inside the constructor implementation). Please help me to come up with a solution.
My system is
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-55)
Working Code
#include <iostream>
#include <string>
#include <map>
using namespace std;
class TestClass{
public:
typedef int (TestClass::*FunctionPtr)(int);
map <string, FunctionPtr> mFnPtrMap;
int Function1( int nAdd ) { return nAdd + 1; }
int Function2( int nAdd ) { return nAdd + 2; }
TestClass() {
mFnPtrMap.insert( make_pair( "Function1", &TestClass::Function1) );
mFnPtrMap.insert( make_pair( "Function2", &TestClass::Function2) );
}
int CallFunction( const string & s, int n ) {
FunctionPtr fp = mFnPtrMap[s];
return (this->*fp)(n);
}
};
int main() {
TestClass ts;
cout << ts.CallFunction( "Function1", 0 ) << endl;
cout << ts.CallFunction( "Function2", 0 ) << endl;
}
What I want to do is:
My expectation is to change it into something like this (use 'this->' instead of 'TestClass::')
mFnPtrMap.insert( make_pair( "Function1", &this->Function1) );
It gives me a compiler error. It even suggests me to use TestClass:: name resolution.
"ISO C++ forbids taking the address of a bound member function to form
a pointer to member function. Say &TestClass::Function1"
Does that mean it's not possible? If someone could give me an explanation also, it would help me to understand the theory underneath. Thank you.
If I had to guess for a reason behind this part of the C++ standard, it's that the types of expressions are hardly equivalent. Just compare how you would need to call the function if in a single expression without the function call as some sort of indirection:
(this->*TestClass::function)(); // Binding the member pointer to an instance
Here we bind the member pointer to an instance with the ->* operator which fills the implicit T* argument each member function has, the one named this. Some other language ask you to provide it explicitely, for example Python but I'm sidetracking a bit.
this->function();
Here the subexpression this->function already bound the parameter of this to the local this object which mean that this does in fact in no way refer to a function. Consequently, you can not take an address of it.
You could argue that this should be allowed as part of the standard but consider the fact that you can shadow function declarations in child classes. That means that introducing a second expression for expressing &TestClass::function would only introduce confusion. In the current form it is very clear which function we are referring to whereas in a this->function form it would not be, especially newcomers might assume that this is completely dynamic as this is not a static object. It would also not be interely unreasonable to assume that there in fact is a difference between the expressions.
In the mean time, I can only offer a way to remove the explicit referal to the class by some type level computations:
#include <type_traits>
template<typename T>
using This = typename std::remove_const<typename std::remove_pointer<T>::type>::type;
TestClass::TestClass() {
mFnPtrMap.insert( make_pair( "Function1", &This<decltype(this)>::Function1) );
mFnPtrMap.insert( make_pair( "Function2", &This<decltype(this)>::Function2) );
}
boost::optional support in_place construction like so:
#include <boost/optional.hpp>
#include <boost/utility/typed_in_place_factory.hpp>
class Foo
{
int a,b;
public:
Foo(int one, int two) : a(one),b(two) {}
};
int main()
{
boost::optional<Foo> fooOpt(boost::in_place<Foo>(1,3));
}
Once we have an initialized fooOpt, is there a way of assigning a new Foo to it without creating a temporary?
Something like :
fooOpt = boost::in_place<Foo>(1,3);
Thanks!
boost::optional
#include <boost/optional.hpp>
int main() {
boost::optional<int> x;
x = boost::in_place(3);
}
We can also show (via code) that this is building the object in-place by making Foo inherit from boost::noncopyable:
#include <boost/optional.hpp>
#include <boost/noncopyable.hpp>
class Foo : boost::noncopyable {
public:
Foo(int one, int two) {}
};
int main() {
boost::optional<Foo> x;
x = boost::in_place(3, 4);
}
std::optional (eventually...)
Eventually, we will get access to std::optional. This type will implement an emplace() method, that will implement in-place construction as well.
#include <optional>
int main() {
std::optional<int> x;
x.emplace(3);
}
boost::optional (soon...)
In version 1.56.0, boost::optional will also implement the emplace() method that I talked about for std::optional. So, let's see that:
#include <boost/optional.hpp>
int main() {
boost::optional<int> x;
x.emplace(3);
}
The documented interface does not support this.
However, if you know that nobody extends boost::optional, I believe this may be technically valid:
template<typename T, typename... Us>
void emplace_replace( boost::optional<T>& target, Us&&... us ) {
target.~boost::optional<T>();
try {
new (&target) boost::optional<T>( boost::in_place( std::forward<Us>(us)...) );
} catch(...) {
new (&target) boost::optional<T>();
throw;
}
}
Here, we destroy the target, then reconstruct a new boost::optional<T> in its place with in-place construction. The try-catch construct should make most throws during construction safe: if it throws, you end up with an empty optional.
This naturally behaves differently than operator= is expected to.
In 1.55 (and maybe earlier?), there is an undocumented operator= that takes an Expr which supports boost::in_place and boost::in_place<T>. See #sharth's answer for a detailed use.
My quick reading indicates that a typed inplace factory via this method may have insufficient guards:
boost::optional<int> test;
// test = boost::in_place<double>( 3 ); // <-- very dangerous
test = boost::in_place( 3 ); // safe
test = boost::in_place( 3.0 ); // safe
If a type is passed directly to in_place<?>, it can generate a typed_in_place_factory, which are dangerous (they make the passed in type, and don't check that it is compatible). So don't pass any types to boost::in_place.
This (from reading the source) does something similar to my destroy/reconstruct code, except it does it without destroying the entire optional and just destroys the stored data and makes it uninitialized.
In boost 1.56b1, emplace has been added to boost::optional. It does something similar to both of the above operations. (via #AkiraTakahashi)
std::optional proposals I have seen have included a member function .emplace( Us&&... ) that supports emplace replacing directly.
Once you know it's there, you could create an ordinary reference:
optional<Foo> optFoo = ....;
Foo &foo = *optFoo;
foo.x = 3;
foofun(foo);
foo = Foo();
Suppose I want to implement a simple abstraction over pthreads.
(or any C API that takes function pointers for callbacks or threads).
Like std::thread, I want the interface to be able to take function objects in general.
How do I bridge the gap in a way that works for all cases?
(That includes binds, lambda functions, etc.)
I know about the std::function::target but afaik, it does not do what I need.
If the API takes functions with a void* for user data as, e.g., pthread_create() does, you'd pass a pointer to the function as user data, call a trampoline which casts the user data to your function type, and calls the function. For example:
#include <functional>
#include <pthread.h>
extern "C" void* trampoline(void* userData) {
return (*static_cast<std::function<void*()>*>(userData))();
}
void* start() {
// ...
return 0;
}
int main() {
pthread_t thread;
std::function<void*()> entry(start);
pthread_create(&thread, 0, &trampoline, &entry);
// ...
}
The immediate implication is, however, that the function object life-time isn't easily controlled. In the example above the std::function<void*()> object happens to live long enough but it isn't always as easy.
If the function you try to call doesn't have a user data argument, you are pretty much out of luck. You might get away with using global objects but it is almost certainly a rather fragile approach.
A lambda function can be used anywhere that takes regular function pointers. In other words, it can be used wherever you would use regular functions/pointers to functions..
Example: https://ideone.com/4CJjlL
#include <iostream>
void voidfunc(void (*func_ptr)(void))
{
func_ptr();
}
void funcwithargs(void (*func_ptr)(int, char, std::string), int a, char b, std::string c)
{
func_ptr(a, b, c);
}
int main()
{
auto vf = []{std::cout<<"Called void func..\n";};
auto vfwa = [](int a, char b, std::string c) {std::cout<<"Called func with args with: "<<a<<b<<" "<<c<<"\n";};
voidfunc(vf);
funcwithargs(vfwa, 10, 'x', " + 3");
return 0;
}
Likewise, you can use std::function instead of the function pointer..
Is it possible, with C++ 11 or Boost, to create an object that stores an object pointer (instance), method pointer and some arguments and can invoke this method with these arguments later? I mean - how to do it using only std or Boost templates? I'm pretty sure it is possible, but don't know what's the best way.
And here's the real question: is it in any way possible to store several such objects that refer to different methods (with diferent signatures) in the same container?
That's the classic use case for std::bind and std::function:
#include <functional>
#include <vector>
using namespace std::placeholders; // for _1, _2, ...
std::vector<std::function<int(double, char)>> v;
Foo x;
Bar y;
v.emplace_back(std::bind(&Foo::f, &x, _1, _2)); // int Foo::f(double, char)
v.emplace_back(std::bind(&Bar::g, &y, _2, true, _1)); // int Bar::g(char, bool, double)
v.emplace_bacK(some_free_function); // int some_free_function(double, char)
To use:
for (auto & f : v) { sum += f(1.5, 'a'); }
Check out std::bind offered by C++11. It does exactly what you want. You don't even need boost for this. For example:
class C
{
public:
void Foo(int i);
}
C c;
// Create a function object to represent c.Foo(5)
std::function<void(void)> callLater=std::bind(&C::Foo,std::ref(c),5);
// Then later when you want to call c.Foo(5), you do:
callLater();
I have 2 functions f() and g(). I want to call them in order every time. Can I get a boost::function to do this?
E.g. something like:
boost::function functor = boost::bind( boost::bind(f), boost::bind(g) );
Extend this further, say it takes arguments, then what I need is a chain of responsibility. Each node does something with arguments, then followed by next node of chain.
How do I do that?
Update Thanks for Seth Carnegie's comments.
I think what I really want is how to construct a chain of responsibility into a single boost::function, each node of chain can be constructed by using boost::bind().
Have you considered using boost::signal ?
With boost::signal you can connect multiple function calls into one.
#include <boost/signal.hpp>
#include <iostream>
void f()
{
std::cout << " Hello" << std::flush;
}
void g()
{
std::cout << " World" << std::endl;
}
int main()
{
boost::signal<void ()> s;
s.connect(f);
s.connect(g);
s();
}
Why not something like this?
#include <functional>
template <typename FirstFunctor, typename SecondFunctor>
void chainFunctionImpl(FirstFunctor first, SecondFunctor second)
{
first();
second();
}
template <typename FirstFunctor, typename SecondFunctor>
std::function<void(void)> chainFunction(FirstFunctor first, SecondFunctor second)
{
return std::bind(chainFunctionImpl<FirstFunctor,SecondFunctor>,first,second);
}
Use should be relatively simple, just binding the functions in sequence, then calling the result. Theoretically any length of functions could be chained up.
Note that is theoretically possible to do this with passing an argument down the chain as well, but that level of template foo is way beyond me. http://ideone.com/Xvp5U is where I gave up.
There is a quite easy solution using boost::lambda with its comma operator. In my case I am using it for a modificator function which is defined as (B is an arbitrary class for e.g. and A is a class which should be altered but resides in B and should not go outside)
void B::modify( boost::function<void(A&)> func );
My intention is to pass only the modificator to the modify function which makes it more easy to gain control when it is modified (for e.g. for emitting signals).
Sometimes I want to apply 2 modifier:
void A::setInvalid();
void A::setX( int x );
Calling in 2 steps which is not the way (just as reference to show how we want to use the modify method):
instanceA->modify(
boost::bind( &A::setInvalid, _1 );
instanceA->modify(
boost::bind( &A::setX, _1, 4 );
Using boost::lambda this can be joined to a single function call and therefore only one function is created:
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
using namespace boost::lambda;
instanceA->modify(
( bind(&A::setInvalid, boost::lambda::_1)
, bind(&A::setX, boost::lambda::_1, 4) ) );
Related to your question this would look then:
using namespace boost::lambda;
boost::function<void()> func = ( bind(f), bind(g) )