2017-11-26 5 views
3

일반 람다를 연구하고 예제를 약간 수정했습니다. 그래서 람다는 상위 람다의 가변 매개 변수 팩을 캡처해야합니다. 그래서 기본적으로 상단 람다에 주어진 것은 (auto&&...)입니다 - 어떻게 든 [=] 블록에 캡처해야합니다. C++ lambdas 상위 범위에서 variadic 매개 변수 팩을 캡처하는 방법

내가 궁금해서,

#include <iostream> 
#include<type_traits> 
#include<utility> 


// base case 
void doPrint(std::ostream& out) {} 

template <typename T, typename... Args> 
void doPrint(std::ostream& out, T && t, Args && ... args) 
{ 
    out << t << " ";    // add comma here, see below 
    doPrint(out, std::forward<Args&&>(args)...); 
} 

int main() 
{ 
    // generic lambda, operator() is a template with one parameter 
    auto vglambda = [](auto printer) { 
     return [=](auto&&... ts) // generic lambda, ts is a parameter pack 
     { 
      printer(std::forward<decltype(ts)>(ts)...); 
      return [=] { // HOW TO capture the variadic ts to be accessible HERE ↓ 
       printer(std::forward<decltype(ts)>(ts)...); // ERROR: no matchin function call to forward 
      }; // nullary lambda (takes no parameters) 
     }; 
    }; 
    auto p = vglambda([](auto&&...vars) { 
     doPrint(std::cout, std::forward<decltype(vars)>(vars)...); 
    }); 
    auto q = p(1, 'a', 3.14,5); // outputs 1a3.14 

    //q(); //use the returned lambda "printer" 

} 

답변

3

완벽한 전달이 또 다른 질문입니다 (완벽한 전달은? 궁금 해요 전혀 여기 수 있으며, 또 다른 질문입니다) 여기가 가능한 모든이다 ?

음 ... 완벽한 전달 이라는 질문입니다.

ts...의 캡처가 잘 작동하면, 내부 람다,

printer(std::forward<decltype(ts)>(ts)...); 

printer(ts...); 

프로그램 컴파일로 변경하는 경우.

문제 ([=] 사용)값으로 ts... 캡처들이 constprinter() 값 (즉 auto&&...vars 수신 람다 인) 수신 레퍼런스 (또는 &&&)되기 때문이다.

대신으로 참조 (그래서 [&]를)로 ts...을 캡처 다음과 같은 기능 그 소리에서

void bar (int &&) 
{ } 

void foo (int const & i) 
{ bar(std::forward<decltype(i)>(i)); } 

++ 내가

tmp_003-14,gcc,clang.cpp:21:4: error: no matching function for call to 'bar' 
{ bar(std::forward<decltype(i)>(i)); } 
    ^~~ 
tmp_003-14,gcc,clang.cpp:17:6: note: candidate function not viable: 1st argument 
     ('const int') would lose const qualifier 
void bar (int &&) 
    ^

를 얻을하여 문제를 해결하는 또 다른 방법은 동일한 문제가있다 볼 수 있습니다 값.