我正在嘗試編寫一個模板函數,它接受取決於模板參數的std::function
。不幸的是,編譯器無法正確消除std::function
的參數。這裏是一些簡單的例子代碼:C++ 11模板函數,它取決於模板參數的std ::函數
#include <iostream>
#include <functional>
using namespace std;
void DoSomething(unsigned ident, unsigned param)
{
cout << "DoSomething called, ident = " << ident << ", param = " << param << "\n";
}
template < typename Ident, typename Param >
void CallFunc(Ident ident, Param param, std::function< void (Ident, Param) > op)
{
op(ident, param);
}
int main()
{
unsigned id(1);
unsigned param(1);
// The following fails to compile
// CallFunc(id, param, DoSomething);
// this is ok
std::function< void (unsigned, unsigned) > func(DoSomething);
CallFunc(id, param, func);
return 0;
}
如果我稱之爲有以下模板:
CallFunc(id, param, DoSomething);
我收到以下錯誤:
function-tpl.cpp:25: error: no matching function for call to
CallFunc(unsigned int&, unsigned int&, void (&)(unsigned int, unsigned int))
如果我明確地創建一個std ::正確類型的功能(或投它)問題消失:
std::function< void (unsigned, unsigned) > func(DoSomething);
CallFunc(id, param, func);
我將如何編碼,以便不需要顯式臨時?
您是否忘記在違規行之前刪除註釋字符「//」?我有GCC4.6.1,GCC拒絕上述線路。 –
@litb * D'OH!* 發現得好。 –