2014-06-23 6 views
1

반환 값을 얻기 위해 형식 공제를 사용하여 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. 
+1

사용할 필요가 없습니다? : D –

+2

나를 기억 나게한다 http://cppquiz.org/quiz/question/109 – chris

+0

지우개 또는 형식 공제 입력 : 하나를 선택하십시오. – Mankarse

답변

4

오류가 무엇 std::function

class WorkQue 
{ 
    public: 
     template<typename Func, typename ...Args> 
     auto addItem(Func && task, Args &&... args) -> std::future<decltype(task(std::forward<Args>(args)...))> 
     { 
      using R = decltype(task(std::forward<Args>(args)...)); 
      std::promise<R>  promise; 
      std::future<R>  future = promise.get_future(); 

      // STUFF 

      return future; 
     } 
}; 

http://coliru.stacked-crooked.com/a/c1a8b02a1fbf5123

+0

'Args && ...'와'decltype (std :: forward (task) (std :: forward (args) ...))'를 사용하면 콜 사이트의 모든 것을 완벽하게 전달할 수 있습니다. – Mankarse

+0

@Mankarse 당신 말이 맞습니다. 'decltype'에서'task'를 포워드 할 필요가 있습니까? –

+0

@BryanChen 필자는 그렇게 생각합니다. 그렇지 않으면'args '중 하나를 복사 할 수 없으면'decltype'이 잘못 형성 될 수 있으며 함수를 SFINAE로 끝낼 것입니다 (그러나이 경우는 확실하지 않습니다). 어쨌든'result_of' 만 사용할 수 있습니다. – Praetorian