2015-08-15 48 views
2

考慮下面的例子:爲什麼std :: bind無法用多個參數解決函數重載?

#include <iostream> 
#include <functional> 

using namespace std; 

void f(int x,int y) {} 
// void f(int x) {} // if this line is uncommented, code does not compile. 

int main() { 
    auto functor = std::bind(&f,1,placeholders::_1); 
    cout << "works!" << endl; 
    return 0; 
} 

它編譯並作爲是運行良好(https://ideone.com/fork/2SywE2),但是在取消對註釋行導致編譯器錯誤:

prog.cpp:在函數「詮釋主()」 : prog.cpp:10:48:error:調用'bind(,int,const std :: _佔位符< 1> &)' auto functor = std :: bind(& f,1,佔位符:: _ 1); ^ 從prog.cpp包含的文件中:2:0: /usr/include/C++/5/functional:1462:5:note:candidate:template typename std :: _ Bind_helper :: value,_Func,_BoundArgs .. 。> ::類型的std ::綁定(_Func & &,_BoundArgs & & ...) 綁定(_Func & & __f,_BoundArgs & & ... __args) ^ 的/ usr /包括/ C++/5 /官能:1462:5:note:template argument deduction/substitution failed: prog.cpp:10:48:note:無法推論模板參數'_Func' auto functor = std :: bind(& f,1,plac eholders :: _ 1); ^ 從prog.cpp包含的文件中:2:0: /usr/include/C++/5/functional:1490:5:note:candidate:template typename std :: _ Bindres_helper < _Result,_Func,_BoundArgs> ::類型的std ::綁定(_Func & &,_BoundArgs & & ...) 綁定(_Func & & __f,_BoundArgs & & ... __args) ^ 的/ usr /包括/ C++/5 /功能:1490:5 :注意:模板參數推導/替換失敗: prog.cpp:10:48:注意:無法推導出模板參數'_Result' auto functor = std :: bind(& f,1,佔位符:: _ 1);

爲什麼標準::綁定無法解析模板參數如果多於一個的過載出現,如過載有輸入參數不同numebr,並調用結合暗示的輸入參數,這個數字是2

回答

1

當C++編譯器看到呼叫std::bind(&f,1,placeholders::_1),它不知道參數之間的任何關係。關係只有在模板被實例化時纔可見。爲了實例化它,編譯器需要模板參數。但是&f是一個重載函數,所以它沒有定義的類型。因此,C++編譯器無法實例化模板,因此即使在可以看到任何關係之前,編譯失敗。

std::bind(static_cast<void(*)(int,int)>(&f),1,placeholders::_1); 

您可以通過顯式地指定類型解決此

相關問題