Perfect functor forwarding

I wonder what the correct way to use a perfect redirected functor? Here are two pieces of code. Which one is the best, and if not, what is the best form?

template<typename T, typename... Args>
void callMe(T&& func, Args&&... args) {
    func(std::forward<Args>(args)...);
}

or

template<typename T, typename... Args>
void callMe(T&& func, Args&&... args) {
    std::forward<T>(func)(std::forward<Args>(args)...);
}

EDIT:

Will this affect overload resolution? If it func operator()has a ref-qualifier for &&or const &, should I use the latest version and should I worry about what overload I'm causing?

Thank!

+3
source share
2 answers

Since ref-qual operator()exists, the first version may be wrong. Consider:

struct C {
    void operator()() && { std::cout << "rval\n"; }
    void operator()() const & { std::cout << "lval\n"; }
};

callMe(C{});

rvalue - "rval" - lvalue, "lval".

, - forward func.


, -, , , .

+3

, (, rvalue) - , , rvalue lvalue. func, .

, std::forward std::move, r-.

, , , , . , const T& .

, , func ref-qual operator(). ( , .) .

: "rvalue reference * this" ?

struct C {
    void operator()() && { std::cout << "rval\n"; }
    void operator()() const & { std::cout << "lval\n"; }
};

callMe(C{});
+5

Source: https://habr.com/ru/post/1628379/


All Articles