jeudi 13 juillet 2023

C++ 11 function composition with helper struct performance overhead

As we know, in C++ 11, can't deduce the return type of function returning lambda with auto or decltype(auto). So can't use code like below.

template <typename F, typename G>
constexpr decltype(auto) compose(const F& f, const G& g) noexcept {
    return [&f,&g](auto&& x){
        return f(g(std::forward<decltype(x)>(x)));
    };
}

Instead, work around like below could be employed;

template <typename F, typename G>
struct Composed
{
    const F &f;
    const G &g;

    Composed(const F &f, const G &g) : f(f), g(g) {}

    template <typename Arg>

    inline auto operator()(Arg &&arg) -> decltype(f(g(std::forward<Arg>(arg))))
    {
        return f(g(std::forward<Arg>(arg)));
    }
};

template <typename F, typename G>
Composed<F, G> compose(const F &f, const G &g)
{
    return Composed<F, G>(f, g);
}

As alway, the actuall performance could be vary by time, but what would be the general performance of this approach compared to lambda capturing lambda? Does adding inline in front of operator() could help? Or still there is inevitable overhead?

Aucun commentaire:

Enregistrer un commentaire