将 boost::bind 与构造函数一起使用
我正在尝试创建新对象并使用 boost::bind 将它们添加到对象列表中。例如。
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)
)
);
这似乎不起作用。有没有办法将构造函数与 boost::bind 一起使用,或者我应该尝试其他方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这取决于
a::some_member
返回的内容 - 如果它是Object
那么您不需要将结果包装在Object
中> ctor——它已经被构建好了。如果例程没有返回Object
,那么您可能需要对结果进行一些处理,您可以使用boost::bind
来提取结果,但可以使用实用程序函数可以使代码更具可读性。无论哪种情况,更多的代码都会有所帮助,特别是
a
和Object
的类型实例。It depends on what
a::some_member
is returning -- if it is anObject
then you shouldn't need to wrap the result in anObject
ctor -- it will have already been constructed. If the routine is not returning anObject
then you're likely going to have to massage the result a bit, which you could pull of withboost::bind
but a utility function may keep the code more readable.In either case, more code would help, specifically the type instance of
a
andObject
.如果您使用的是 boost 1.43,则可以使用 boost::factory 和 boost::value_factory,它们可以让您封装构造函数调用。
像这样:
If you are using boost 1.43, you can use boost::factory and boost::value_factory, which let you encapsulate a constructor invocation.
Like this:
如果
Stuff::some_member
是int
并且Object
有一个采用int
的非显式 ctor,那么这应该可以工作:否则,您可以使用 boost:: lambda::构造函数
If
Stuff::some_member
isint
andObject
has a non-explicit ctor taking anint
, this should work:Otherwise, you could use boost::lambda::constructor
Éric 的链接部分指出“不可能获取构造函数的地址,因此构造函数不能用作绑定表达式中的目标函数。”所以我想做的事情是不可能的。
我通过创建一个函数来解决这个问题:
并在我试图使用对象构造函数的地方使用 Object_factory 。
É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:
and using Object_factory where I was trying to use the Object constructor.