mercredi 30 janvier 2019

Efficient way of returning a lambda in a function that needs a call to an object

Following up from this past post:

A user stated:

Are you comfortable using lambdas in C++11? If yes, you simply need to return one from first_function(), and then you call the lambda in perform_action(). Of course, you need to pass the parameter to the lambda, but you wouldn't need to pass it to first_function()

I'm not quite sure how to do this or if this is even a good idea past on this other stackoverflow post

Just keep in mind that std::function employs type erasure, which can mean the cost of making a virtual function call when calling the std::function. Something to be aware of if the returned function is going to be used in a tight inner loop or other context where the slight inefficiency matter. – Anthony Hall

The call to the perform_action function template will be called in a loop. I don't understand if what Anthony above, will affect me since I plan to use that function call inside a class method.

Here's a snippet from the post link above:

// class that uses the shared_ptr

class setter {
private:

std::shared_ptr<Base> l_ptr;

public:

setter(const std::shared_ptr<Base>& input):l_ptr(input)
{}

int get_thing_a()
{
    return perform_thing<THINGA>(..);
}

int get_thing_b()
{
    return perform_thing<THINGB>(..);
}
};

So what I really want to know is if its recommended to use this solution posted:

template <>
struct thing_traits<THINGA>
{
    static int (Base::*first_function)() = &Base::get_thing_one;
    ...
}

template < thing_select T,  typename TT = thing_traits<T>>
int perform_action(Base & b)
{
   return (b.*TT::first_function)() + ...;
}

Or the suggestion of modifying it to return a lambda function instead. If so, would this mean passing the Base class parameter as a "capture" to the lambda?

If I do use a lambda, when is it appropriate to use std::function vs a function pointer (using C++11). I didn't find a lot (or didn't know how to term the search) for my case of objects calling lambda functions, from a static function in the traits class. A drafted example would help.

Aucun commentaire:

Enregistrer un commentaire