【发布时间】:2014-06-23 23:01:54
【问题描述】:
尝试将 lambda 作为参数传递给采用 std::function 的函数,然后使用类型推导获取返回值。但是编译失败。
#include <future>
class WorkQue
{
public:
template<typename R, typename ...Args>
std::future<R> addItem(std::function<R(Args...)> task, Args... args)
{
std::promise<R> promise;
std::future<R> future = promise.get_future();
// STUFF
return future;
}
};
int main()
{
WorkQue que;
int x = 1;
int y = 2;
// This fails
que.addItem([](int x, int y){return x+y;}, x, y);
// I can see needing to specify the return type.
// But even this does not work.
// que.addItem<int>([](int x, int y){return x+y;}, x, y);
// This works fine.
// But I was hoping not to need to specify this every time.
//que.addItem<int>(std::function<int(int,int)>([](int x, int y){return x+y;}), x, y);
}
编译错误是:
> g++ -std=c++1y thread.cpp
thread.cpp:24:9: error: no matching member function for call to 'addItem'
que.addItem([](int x, int y){return x+y;}, x, y);
~~~~^~~~~~~
thread.cpp:9:24: note: candidate template ignored: could not match 'function<type-parameter-0-0 (type-parameter-0-1...)>' against '<lambda at thread.cpp:24:17>'
std::future<R> addItem(std::function<R(Args...)> task, Args... args)
^
1 error generated.
【问题讨论】:
-
类型擦除或类型扣除:二选一。
-
还有,请问是什么问题?
标签: c++ templates lambda template-meta-programming c++14