tr1 :: mem_fn和带有默认参数的成员 [英] tr1::mem_fn and members with default arguments
问题描述
我有一个类成员函数,它接受一个默认参数。
I have class with a member function that takes a default argument.
struct Class
{
void member(int n = 0)
{}
};
通过std :: tr1 :: mem_fn我可以调用它:
By means of std::tr1::mem_fn I can invoke it:
Class object;
std::tr1::mem_fn(&Class::member)(object,10);
也就是说,如果我想调用对象上的使用默认参数,语法是什么?
That said, if I want to invoke the callable member on the object with the default argument, what's the correct syntax?
std::tr1::mem_fn(&Class::member)(object); // This does not work
g ++抱怨出现以下错误:
g++ complains with the following error:
test.cc:17: error: no match for call to ‘(std::tr1::_Mem_fn<void (Class::*)(int)>) (Class&)’
/usr/include/c++/4.3/tr1_impl/functional:551: note: candidates are: _Res std::tr1::_Mem_fn<_Res (_Class::*)(_ArgTypes ...)>::operator()(_Class&, _ArgTypes ...) const [with _Res = void, _Class = Class, _ArgTypes = int]
/usr/include/c++/4.3/tr1_impl/functional:556: note: _Res std::tr1::_Mem_fn<_Res (_Class::*)(_ArgTypes ...)>::operator()(_Class*, _ArgTypes ...) const [with _Res = void, _Class = Class, _ArgTypes = int]
由接受不同参数的成员重载...
Still, the I have the same problem when Class::member is overloaded by members that takes different arguments...
推荐答案
默认函数在调用时绑定,进入任何种类的包装器,因为它们的实现方式。当你通过& Class :: member
, mem_fn
:*)(int),并且看不到默认参数。使用 tr1 :: bind
,可以明确绑定默认参数: std :: tr1 :: bind(& Class :: member,0)
或者你可以使用它,因为你会 mem_fn
,但是你不能在一个对象。
Default functions are bound at call time, but can't be bound into any sort of wrapper implicitly, because of the way they are implemented. When you pass &Class::member
, mem_fn
only sees a void (Class::*)(int)
, and can't see the default argument. Using tr1::bind
, you can bind the default argument explictly: std::tr1::bind(&Class::member, 0)
or you can use it as you would mem_fn
, but you can't do both in one object. You would have to write your own wrapper class for that.
对于重载,你必须明确指定 mem_fn
As for overloads, you will have to explicitly specify the template arguments for mem_fn
so the right function pointer is picked as in mem_fn<void(int)>(&Class::member)
.
这篇关于tr1 :: mem_fn和带有默认参数的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!