![](/img/trans.png)
[英]Invalid static_cast from type <unresolved overloaded function type>
[英]Why function pointer of overloaded function need static_cast?
對於下面的代碼,我收到錯誤
#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(N::func);
作為func_1(static_cast<void (&)(A, int)>(N::func));
,那么這個工作正常。 但我希望這在沒有演員的情況下工作。
std::function<void(A, int)>
比void(*)(A, int)
更復雜。
template< class F > function( F f );
用
std::move(f)
初始化目標。 如果f
是指向函數的空指針或指向成員的空指針,則調用后*this
將為空。 除非f
對於參數類型Args...
和返回類型R
是可調用的,否則此構造函數不參與重載決議。
在您決定哪個N::func
之前,您甚至不知道哪些構造函數參與了重載決議。
通過嘗試std::function<void(A, int)>::function<void(*)(A, int)>
(任意多個)構造函數的其他有效實例。
問題比比皆是。
int g(A, int)
您還希望它能夠選擇int(*)(A, int)
int g(A, int)
。作為一種方便的解決方法,您可以提供這種func_1
重載。
...
void func_1(void(*x)(A, int))
{
func_1(std::function<void(A, int)>{x});
}
現在它可以在沒有static_cast
情況下正常工作:演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.