c++ - Perfectly capturing a perfect forwarder (universal reference) in a lambda -
so have perfect forwarder, , want appropriately capture in lambda, such r-values copied in, , l-values captured reference. using std::forward doesn't job, evidenced code:
#include<iostream> class testclass { public: testclass() = default; testclass( const testclass & other ) { std::cout << "copy c" << std::endl; } testclass & operator=(const testclass & other ) { std::cout << "copy a" << std::endl; } }; template< class t> void testfunc(t && t) { [test = std::forward<t>(t)](){}(); } int main() { testclass x; std::cout << "please no copy" << std::endl; testfunc(x); std::cout << "done" << std::endl; std::cout << "copy here" << std::endl; testfunc(testclass()); std::cout << "done" << std::endl; }
compiling
g++ -std=c++14 main.cpp
produces output
please no copy copy c done copy here copy c done
in perfect world, have "copy c" appear in rvalue case, not lvalue case.
my work around use helper function overloaded l- , r- values, wondering if there better way.
cheers!
you may use following:
[test = std::conditional_t< std::is_lvalue_reference<t>::value, std::reference_wrapper<std::remove_reference_t<t>>, t>{std::forward<t>(t)}]
but providing helper function seems more readable
Comments
Post a Comment