samedi 29 octobre 2016

std::forward and ref-qualifiers for member functions

I was in a position where I was using std::forward wherever I had a forwarding reference and I was wondering if some of that was unnecessary or even wrong. For example having std::forward in a std::begin() call.

Because of the ability of a class being able to overload its member functions based on whether the call is made with the object as an rvalue or not http://ift.tt/1jM7Wvb, I assumed that a templated function would be as efficient as possible if you were knew that the inner function you were forwarding the object to was non-mutating and/or was a member function of the object. For example

template <typename Something>
void do_something(Something&& something) {
    std::forward<Something>(something).do_something();
    auto iter = std::begin(std::forward<Something>(something));
    for_each(iter, std::end(std::forward<Something>(something), []() {});
}

I saw this question (When not to use std::forward with r-values?) but it did not address the member function ref-qualifiers and it also did not clearly address what the best practice is when you don't have access to the inner functions definitions that you are calling.

Is there a general guideline for when not to use std::forward that addresses the things I mentioned? Or is there some key concept that I am missing?

Aucun commentaire:

Enregistrer un commentaire