我想了解爲什麼std::function
無法區分重載函數。std ::函數無法區分重載函數
#include <functional>
void add(int,int){}
class A {};
void add (A, A){}
int main(){
std::function <void(int, int)> func = add;
}
在上面所示的代碼,function<void(int, int)>
只能匹配的這些功能中的一個,但它失敗。這是爲什麼?我知道我可以通過使用實際函數的lambda或函數指針來解決此問題,然後將函數指針存儲在函數中。但爲什麼這會失敗?上下文不清楚我想選擇哪個功能?請幫我理解爲什麼這會失敗,因爲我無法理解爲什麼模板匹配在這種情況下失敗。是
,我得到鐺這個編譯器錯誤如下:
test.cpp:10:33: error: no viable conversion from '<overloaded function type>' to
'std::function<void (int, int)>'
std::function <void(int, int)> func = add;
^ ~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_03:1266:31: note:
candidate constructor not viable: no overload of 'add' matching
'std::__1::nullptr_t' for 1st argument
_LIBCPP_INLINE_VISIBILITY function(nullptr_t) : __f_(0) {}
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_03:1267:5: note:
candidate constructor not viable: no overload of 'add' matching 'const
std::__1::function<void (int, int)> &' for 1st argument
function(const function&);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_03:1269:7: note:
candidate template ignored: couldn't infer template argument '_Fp'
function(_Fp,
^
1 error generated.
編輯 - 除了MSalters的回答,我沒有在這個論壇上一些搜索和發現的確切原因失敗。我在post得到了納瓦茲回覆的答案。
int test(const std::string&) {
return 0;
}
int test(const std::string*) {
return 0;
}
typedef int (*funtype)(const std::string&);
funtype fun = test; //no cast required now!
std::function<int(const std::string&)> func = fun; //no cast!
那麼,爲什麼std::function<int(const std::string&)>
不起作用funtype fun = test
以上的工作方式:
我已經複製從他的回答粘貼在這裏?
那麼答案是,因爲std::function
可以用任何物體,如其構造是模板化是獨立的,你傳遞給std::function
模板實參的初始化。
哪個編譯失敗呢? – EdChum
gcc 4.8,clang和Visual Studio 2013。如果需要,我可以發佈編譯器錯誤,儘管它們不是非常友好。 – Madhusudhan
編譯錯誤通常不友好但值得發佈它,這很奇怪,這在這裏變得模糊不清,就好像A類的類型在某種程度上被看作與'int'一樣,如果你聲明瞭錯誤仍然會發生'加'作爲'雙'? – EdChum