gpt4 book ai didi

c++ - 无法获取 std::bind() 返回对象的 operator() 指针

转载 作者:行者123 更新时间:2023-12-05 02:34:27 26 4
gpt4 key购买 nike

我需要提取函数对象参数的类型。

Lambdas 使用 operator() 转换为闭包对象。 std::function 也有 operator()

因此,我可以通过这种方式获取指向 operator() 的指针以传递给另一个函数:

template <typename F, typename T, typename R, typename ... Args>
void helper(F&, R (T::*)(Args...) const)
{
// do something with Args types
}

template <typename F>
void bar(F f)
{
helper(f, &F::operator());
}

void freefunc(int) {}

void foo()
{
// lambda: ok
bar([](int){});
// std::function: ok
const std::function<void(double)> f = [](double){};
bar(f);
// std::bind: does not compile
auto g = std::bind(freefunc, std::placeholders::_1);
bar(g);
}

std::bind 也应该使用 operator() 创建一个对象。但是,我的代码不适用于 std::bind(),我不明白为什么。

gcc 产生这个错误:

In instantiation of 'void bar(F) [with F = std::_Bind<void (*(std::_Placeholder<1>))(int)>]':
<source>:58:8: required from here
<source>:47:11: error: no matching function for call to 'helper(std::_Bind<void (*(std::_Placeholder<1>))(int)>&, <unresolved overloaded function type>)'
47 | helper(f, &F::operator());
| ~~~~~~^~~~~~~~~~~~~~~~~~~
<source>:39:6: note: candidate: 'template<class F, class T, class R, class ... Args> void helper(F&, R (T::*)(Args ...) const)'
39 | void helper(F&, R (T::*)(Args...) const)
| ^~~~~~
<source>:39:6: note: template argument deduction/substitution failed:
<source>:47:11: note: couldn't deduce template parameter 'T'
47 | helper(f, &F::operator());
| ~~~~~~^~~~~~~~~~~~~~~~~~~
ASM generation compiler returned: 1
<source>: In instantiation of 'void bar(F) [with F = std::_Bind<void (*(std::_Placeholder<1>))(int)>]':
<source>:58:8: required from here
<source>:47:11: error: no matching function for call to 'helper(std::_Bind<void (*(std::_Placeholder<1>))(int)>&, <unresolved overloaded function type>)'
47 | helper(f, &F::operator());
| ~~~~~~^~~~~~~~~~~~~~~~~~~
<source>:39:6: note: candidate: 'template<class F, class T, class R, class ... Args> void helper(F&, R (T::*)(Args ...) const)'
39 | void helper(F&, R (T::*)(Args...) const)
| ^~~~~~
<source>:39:6: note: template argument deduction/substitution failed:
<source>:47:11: note: couldn't deduce template parameter 'T'
47 | helper(f, &F::operator());

std::bind 做同样的事情的正确方法是什么?

最佳答案

不幸的是,你想做的是不可能的,因为 std::bind 的返回类型被标准指定得太松散。

  • std::function::operator() 由标准明确定义,因此您可以将其与 R (T::*)(Args... ),请参阅 [func.wrap.func.general] ,
  • 对于 lambda 函数,[expr.prim.lambda.closure#3] 不是很清楚,但我认为它应该有效,
  • 对于 std::bind,规范 [func.bind.bind#4]更广泛,因为它只说你可以调用 g(u1, u2, …, uM) 其中 gstd::bind< 的返回值,所以不能保证 std::bind 的返回类型甚至有一个 operator() 成员函数。

这里的实际实现问题与 gcc、clang 和 msvc 相同,是返回值的 operator() 成员函数实际上是一个模板,因此您不能使用 &F::operator() 直接 — 您不能获取模板化(成员)函数的地址。

关于c++ - 无法获取 std::bind() 返回对象的 operator() 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70753352/

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