lundi 25 avril 2016

How to forward lvalue reference?

I have this code:

struct MultiMemoizator {
    template <typename ReturnType, typename... Args>
    ReturnType callFunction(std::function<ReturnType(Args...)> memFunc, const Args&... args) {
         return memFunc(args ...);
    }
};

int main()
{
    typedef vector<double> vecD;
    //filling vecD with random numbers...
    MultiMemoizator mem;
    function<vecD(vecD)> sort_vec = [](const vecD &vec) {
        sort(vec.begin(),vec.end());
        return vec;
    };
    mem.callFunction<vecD,vecD>(sort_vec,vec);
    //vec is still not sorted!
}

Since memFunc(args ...); what happens is that a copy of args is sorted and not vec, so at the end vec will be unsorted after callFunction(...).

I think that in order to solve this problem forward can help me, but if I try: return cachedFunc(forward<Args>(args) ...); then something bad happens (like vector::size=0).

How can I forward args reference to sort_vec?

Aucun commentaire:

Enregistrer un commentaire