如何将重载的成员函数作为参数传递?

时间:2019-07-16 16:54:13

标签: c++ class c++11 member-function-pointers std-function

这是我面临的问题:我在一个类中有一个重载的函数,并且我想将其重载之一作为参数传递。但是这样做时,出现以下错误:

"no suitable constructor exists to convert from <unknown-type> to std::function<...>"

这里有一个代码示例来说明:

#include <functional>
#include <string>

class  Foo
{
private:
    int val1 , val2;
};    

class Bar
{
public:
    void function ( ) {
        //do stuff;
        Foo f;
        function ( f );
    }    
    void function ( const Foo& f ) {
        //do stuff
    }

private:
    //random attribute
    std::string str;    
};


void otherFunction ( std::function<void ( Bar& , const  Foo& ) > function ) {
    Bar b;
    Foo f;
    function(b,f);
}

int main ( ) {    
    otherFunction ( &Bar::function );
                    ^^^
                   error
}

我了解编译器无法推断出要使用的重载,因此下一个最好的选择是static_cast,但是以下代码仍然具有相同的错误

std::function<void ( Bar& , const Foo& )> f = static_cast< std::function<void ( Bar& , const Foo& )> > ( &Bar::function );

3 个答案:

答案 0 :(得分:5)

您需要转换为成员函数指针,而不是std::function

otherFunction ( static_cast<void(Bar::*)(const Foo&)>(&Bar::function) );

Live

[编辑]

说明:

otherFunction ( &Bar::function );

otherFunctionstd::function作为参数。 std::function具有来自函数指针(成员函数或自由函数以及其他“可调用”类型,在这里无关紧要)的隐式构造函数(隐式转换)。看起来像这样:

template< class F > 
function( F f );
  • 这是模板参数
  • F是“可调用的”时,它没有指定F的签名

这意味着编译器不知道您的意思是Bar::function,因为此构造函数对输入参数没有任何限制。这就是编译器所抱怨的。

您尝试过

static_cast< std::function<void ( Bar& , const Foo& )> > ( &Bar::function );

虽然看起来编译器具有此处所需的所有详细信息(签名),但实际上调用了相同的构造函数,因此没有任何有效更改。 (实际上,签名是不正确的,但即使是正确的签名也无法使用)

通过强制转换为函数指针,我们提供其签名

static_cast<void(Bar::*)(const Foo&)>(&Bar::function)

解决了歧义,因为只有一个这样的函数,编译器很高兴。

答案 1 :(得分:3)

如果将类型化的成员函数指针与模板化的otherFunction一起使用,则代码将起作用。也就是说,将您的otherFunction()更改为:

template<typename Class, typename T>
void otherFunction(void(Class::*)(T) ) {
    Bar b;
    Foo f;
    b.function(f);
}

如果语法令人困惑,请为成员函数指针使用帮助器(模板)别名:

template<typename Class, typename T>
using MemFunPtr = void(Class::*)(T);

template<typename Class, typename T>
void otherFunction(MemFunPtr<Class, T> function) {
    Bar b;
    Foo f;
    b.function(f);
}

现在,您可以调用函数,而无需进行类型转换

int main()
{
    otherFunction(&Bar::function);
    return 0;
}

See Online

答案 2 :(得分:2)

您可能需要使用宏以避免出现一些麻烦。

#define OVERLOADED(f) \
  [&](auto&&...xs)noexcept->decltype(auto)\
    {return std::invoke(f, decltype(xs)(xs)...);}

int main(){
  g(OVERLOADED(&Bar::function));
}