mardi 4 juin 2019

std:any throwing exception resolving function type

I am running into a problem while resolving a function type from std::any.

I'm basically wrapping a function and it's initial arguments in a lambda function and calling it later point to invoke the wrapped function, but with new set of arguments. This is how the wrapped function looks like.

void Hello(std::string str)
{
    LOG(str);
}

And I'm trying to accomplish the wrapper lambda like this: I have a lambda function that either executes the wrapped functions, and/or otherwise simply returns the wrapped function.

template<typename FuncName, typename... FuncArgs>
bool MMM(std::string EventName, FuncName&& EventFunction, FuncArgs&&... Args) noexcept
{
     //Storing lambda here                
     auto fPtr = std::function<std::any(bool)>([=](bool x)
                                               {
                                                    if(x){
                                                            EventFunction(Args...);
                                                    }
                                                    return (FuncName)EventFunction;
                                                });
}

Now when I try to invoke this lamdba like this:

template<typename E, typename FuncName, typename... FuncArgs>
bool AAA(E EventName, FuncName &&EventFunction, FuncArgs&&... Args)
{
    try {
    //resolving lambda and invoking it here
            auto func = std::any_cast<decltype(EventFunction)>(fPtr)(false));
            func(Args...);
    } catch (...) {
             std::cout<<"Didn't invoke function: Mismatch argument type.\n";
    }
    return true;
}

I'm calling this function in following ways:

MMM(e, Hello, "Hello Florida");
MMM(e, Hello, "Hello USA");

AAA(e, Hello, "Hello World");

Problem: When function AAA is called, I get an exception which says auto_cast failed to resolve the function type.

In the runtime, I see (fPtr)(false) is returning:

std::__1::function<std::__1::any (bool)>     Function = Hello(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) 

while seems like decltype(EventFunction) is of type

void (&)(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) 0x0000000100012540

This seems like I'm almost close to what std::any has stored inside, but still missing out with something which I don't understand what! How do I resolve this std::any_cast mismatch?

Aucun commentaire:

Enregistrer un commentaire