gpt4 book ai didi

c++ - 为什么重载函数的函数指针需要static_cast?

转载 作者:行者123 更新时间:2023-12-03 06:50:09 25 4
gpt4 key购买 nike

对于下面的代码,我收到错误

#include <iostream>
#include <functional>

using namespace std;

class A {};
class B {};

namespace N
{
void func(A a, int z){}
void func(B a, int z){}
}

void func_1(std::function<void(A, int)> x)
{
A a;
x(a, 1);
}

int main()
{
func_1(N::func);

return 0;
}
错误:
    main.cpp:23:19: error: cannot resolve overloaded function 'func' based on conversion to type 'std::function<void(A, int)>'
23 | func_1(N::func);
如果我们对 func_1(N::func); 进行静态转换如 func_1(static_cast<void (&)(A, int)>(N::func)); ,那么这个工作正常。但我希望这在没有 Actor 的情况下工作。

最佳答案

std::function<void(A, int)>void(*)(A, int)更复杂.

template< class F >
function( F f );

Initializes the target with std::move(f). If f is a null pointer to function or null pointer to member, *this will be empty after the call. This constructor does not participate in overload resolution unless f is Callable for argument types Args... and return type R.


您甚至不知道哪些构造函数参与了重载解析,直到您决定哪个 N::func你的意思是。
可以通过尝试 std::function<void(A, int)>::function<void(*)(A, int)> 来设想一种可以“在中间相遇”的组合重载决议和模板参数推导方案。在(任意多个)构造函数的其他有效实例中。
问题比比皆是。
  • 它必须得到可证明的答案。一般来说,模板有无限可能的实例化。您还希望它能够选择 int(*)(A, int)如果你通过了 int g(A, int) .
  • 它确实应该同意当前的方案,得出明确的答案。
  • 每个编译器供应商都必须正确实现它。
  • 关于c++ - 为什么重载函数的函数指针需要static_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64447158/

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