views:

558

answers:

4

I'm trying to create new objects and add them to a list of objects using boost::bind. For example.

struct Stuff {int some_member;};
struct Object{
    Object(int n);
};
....
list<Stuff> a;   
list<Object> objs;
....
transform(a.begin(),a.end(),back_inserter(objs), 
  boost::bind(Object,
     boost::bind(&Stuff::some_member,_1)
  )
);

This doesn't appear to work. Is there any way to use a constructor with boost::bind, or should I try some other method?

A: 

It depends on what a::some_member is returning -- if it is an Object then you shouldn't need to wrap the result in an Object ctor -- it will have already been constructed. If the routine is not returning an Object then you're likely going to have to massage the result a bit, which you could pull of with boost::bind but a utility function may keep the code more readable.

In either case, more code would help, specifically the type instance of a and Object.

fbrereto
I changed the code a bit. Lets say I have a Object(int) constructor and Stuff::some_member is an int. Basically my question is, can anything of the form boost::bind(Object,...) ever work, or are constructors just not allowed as an argument to bind?
Dan Hook
+3  A: 

If Stuff::some_member is int and Object has a non-explicit ctor taking an int, this should work:

list<Stuff> a;   
list<Object> objs;
transform(a.begin(),a.end(),back_inserter(objs), 
  boost::bind(&Stuff::some_member,_1)
);

Otherwise, you could use boost::lambda::constructor

Éric Malenfant
I simplified my code a little too much. The constructor in my real code took three arguments, so in implicit conversion trick doesn't work. The link answered my question completely though. Thanks.
Dan Hook
+1  A: 

Éric's link says, in part "It is not possible to take the address of a constructor, hence constructors cannot be used as target functions in bind expressions." So what I was trying to do was impossible.

I got around it by creating a function:

Object Object_factory(int n)
{  return Object(n); }

and using Object_factory where I was trying to use the Object constructor.

Dan Hook