mercredi 29 mars 2017

casting a function back to the original signature using variadic args

I've found this interesting code here on stackoverflow from: Using a STL map of function pointers

template<typename T,typename... Args>
    T searchAndCall(std::string s1, Args&&... args){

// ....
        // auto typeCastedFun = reinterpret_cast<T(*)(Args ...)>(mapVal.first);
        auto typeCastedFun = (T(*)(Args ...))(mapVal.first);

        //compare the types is equal or not
        assert(mapVal.second == std::type_index(typeid(typeCastedFun)));
        return typeCastedFun(std::forward<Args>(args)...);
    }
};

Basically, mapVal is a map of function pointers casted to void(*)(void) that will be casted back to their original type with this function. What I would like to do know is how typeCastedFun will be deduced when you don't specify the template parameters.

For instance, let's suppose that you had int f(const MyClass& a, MyClass b) {...}

if you have:

MyClass first, second; searchAndCall(first, second);

What Args... parameter will be deduced? if I recall correctly, using the function casted back to a function with a different signature compared to the original one, should yield undefined behavior. Is there any other alternative?

What I would like to do is a way to store the type of the function somewhere and use this information to do the correct cast. Everything in the most efficient way.

Thanks

Aucun commentaire:

Enregistrer un commentaire