gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:12:42 25 4
gpt4 key购买 nike

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

"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 );

最佳答案

您需要转换为成员函数指针,而不是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)

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

关于c++ - 如何将重载的成员函数作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57062131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com