jeudi 24 août 2017

Why std::forward<> , Can't compiler always do the correct thing by default

std::forward<> being the conditional cast , why compiler can't do the work automatically when it sees the parameter which user is trying to pass to other function came as Universal reference.

Means why compiler will place the onus of doing right thing on user by way of writing std::forward.

taking example from Effective modern C++.

void process(const Widget& lvalArg); // process lvalues
void process(Widget&& rvalArg); // process rvalues

template<typename T> // template that passes
void logAndProcess(T&& param) // param to process
{
    auto now = // get current time
    std::chrono::system_clock::now();
    makeLogEntry("Calling 'process'", now);
    process(std::forward<T>(param));
}

In above code sample I know removing std::forward will choose the incorrect overload for process , but to do the right thing of choosing correct overload why user need to write std::forward<> , I mean can't compiler do the obvious for us and for user who don't want to do the correct thing , we can have std::dont_forward<> instead.

I might be missing some use case where compiler can be confused to what's correct but in above case where param being universal reference and two overload of process given to compiler I don't see any confusion.

Any help is appreciated in this regard.

Aucun commentaire:

Enregistrer un commentaire