Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Determine instance of foo in templated function pointer argument call

I'm playing around with function-pointer calls and callbacks and trying to write a function which can take any function-pointer, log the function call and call the function-pointer after. Here is a code to show you what I'm trying to do:

#include<iostream>
#include<string>
#include<functional>

int foo4(std::function<int(int)> Fn, int&& val)
{
    return Fn(std::forward<int>(val));
}

template<typename Fn>
int foo5(Fn fn)
{
    return 10;
}

template <typename T, typename... args>
T(*LogAndCall(T(*ptr)(args...)))(args...)
{
    std::cout << "Logging function call to: " << ptr << " with " << sizeof...(args) << " argument(s)" << std::endl;
    return ptr;
}

int main()
{
    //call func1
    auto r4 = LogAndCall(foo4)([](int&& x) {
        return x * 10;
    }, 100);
    std::cout << "Ret value: " << r4 << std::endl << std::endl;

    //call foo5
    auto r5 = LogAndCall(foo5<specialization?>)([](int x) { //<--- problem
        return x;
    });

    std::cin.get();
    return 0;
}

As you can see, the problem is with calling foo5 with the following error:

Looks like I need to specify foo5<something> but the question is, what? :)


1 Answers

Looks like I need to specify foo5<something> but the question is, what?

For a non-capturing lambda you can force decay to a pointer:

auto r5 = LogAndCall(foo5<int(int)>)([](int x){
//                        ~~~~~~~^
    return x;
});

If it's a capturing lambda, you can use a type erasing technique:

auto r6 = LogAndCall(foo5<std::function<int(int)>>)([&](int x){
//                        ~~~~~~~~~~~~~~~~~~~~~~^
    return x;
});

Alternatively, you can store your lambda to a variable so that you can query its type with the decltype() specifier:

auto lambda = [&](int x){
    return x;
};
auto r7 = LogAndCall(foo5<decltype(lambda)>)(lambda);
//                        ~~~~~~~~~~~~~~~^

DEMO

like image 78
Piotr Skotnicki Avatar answered Mar 13 '26 00:03

Piotr Skotnicki