Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between lambda and member function pointer

Tags:

c++

std-ranges

In my answer here, Barry pointed out that it's better to call views::transform(&Planter::getPlants) because views::transform([](Planter const& planter){... accidentally copies.

#if 1
    auto plants = planters
        | std::views::transform([](Planter const& planter){ return planter.getPlants();})
        | std::views::join
        | std::views::common
        ;
// Plant copy constructor
// Plant copy constructor
// Plant copy constructor
// Plant copy constructor
// Plant copy constructor
#else
    auto plants = planters
        | std::views::transform(&Planter::getPlants)
        | std::views::join
        ;
#endif
// Plant copy constructor
// Plant copy constructor

Here Plant is a wrapper around int and Planter is a wrapper around std::vector<int>.

https://godbolt.org/z/dr7PM5Tvd

like image 718
Tom Huntington Avatar asked Aug 02 '26 07:08

Tom Huntington


1 Answers

Oh I actually know this one. The deduced return type of the lambda actually decays the const ref qualifiers of getPlants.

You can fix this by declaring the return type of the lambda to be decltype(auto)

views::transform([](Planter const& planter) -> decltype(auto){...});

https://godbolt.org/z/ocK5PG1z1

like image 158
Tom Huntington Avatar answered Aug 04 '26 20:08

Tom Huntington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!