C++ - 在模板化函数指针参数调用中确定 foo 的实例

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

我正在研究函数指针调用和回调,并尝试编写一个可以接受任何函数指针、记录函数调用并在之后调用函数指针的函数。这是向您展示我正在尝试做的事情的代码:

#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;
}

如您所见,问题在于调用 foo5 时出现以下错误:

看来我需要指定 foo5<something> 但问题是,什么? :)

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

对于非捕获 lambda,您可以强制衰减到指针:

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

如果是捕获 lambda,您可以使用类型擦除技术:

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

或者,您可以将 lambda 存储到一个变量中,以便您可以使用 decltype() 说明符查询其类型:

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

DEMO