我仍然在努力與一些C++語法。
這次我想添加lambda的額外參數。但是,爲了使代碼通用I螞蟻能夠接受任何函數及其參數:我想通過一個lambda作爲參數與模板可變參數
#include <functional>
#include <exception>
template<typename R>
class Nisse
{
private:
Nisse(Nisse const&) = delete;
Nisse(Nisse&&) = delete;
Nisse& operator=(Nisse const&) = delete;
Nisse& operator=(Nisse&&) = delete;
public:
//Nisse(std::function<R()> const& func) {} // disable for testing
template<typename... Args>
Nisse(std::function<R(Args...)> const& func, Args... a) {}
};
int main()
{
// I was hoping this would deduce the template arguments.
Nisse<int> nisse([](int a,double d){return 5;},12,12.0);
}
這產生:
> g++ -std=c++0x Test.cpp
Test.cpp:21:61: error: no matching function for call to ‘Nisse<int>::Nisse(main()::<lambda(int, double)>, int, double)’
Test.cpp:21:61: note: candidate is:
Test.cpp:16:9: note: template<class ... Args> Nisse::Nisse(const std::function<R(Args ...)>&, Args ...)
我試圖明確指定模板類型:
Nisse<int> nisse<int,double>([](int a,double d){return 5;},12,12.0);
但是這個(對我來說令人驚訝)是一個語法錯誤:
> g++ -std=c++0x Test.cpp
Test.cpp: In function ‘int main()’:
Test.cpp:21:23: error: expected initializer before ‘<’ token
Test.cpp:21:65: error: expected primary-expression before ‘,’ token
Test.cpp:21:73: error: expected ‘;’ before ‘)’ token
如果您想從Args ... args參數中推導出Args ...包,那麼[This answer](http://stackoverflow.com/a/11774533/500104)可能會對您有所幫助。如果你期望那些從'std :: function'推導出來的,你[運氣不好](http://stackoverflow.com/a/14784584/500104)。另外,我通常建議只接受'F f,Args ... args'。 – Xeo 2013-02-14 17:58:59
請注意,我更改了我的評論,您可能需要重新閱讀它。 – Xeo 2013-02-14 18:00:59