converting a c++ lambda to a c function

我的未来我决定 提交于 2019-12-05 18:16:55

One way to avoid using a function pointer value within your registration code is to make it a template argument. Unfortunately, I can't quite come up with a really nice notation. However, if it is acceptable to register a function using something like below, it is fairly straight forward to do:

RegisterHelper<decltype(foo)>::doRegister<&foo>("foo");

With this, RegisterHelper is class template with a static function doRegister() which gets the function pointer as template argument. It would be nice to find a way to call a function template directly and have it figure out the type:

doRegister<&foo>("foo");

However, I haven't found a way to do this because function templates cannot be partially specialized (otherwise I think it would be possible). Below is a rough outline of how the code could look. The code doesn't try to do any of the delegation you'd need to do to actually call the function. It is merely intended to show how a function pointer can be passed in. The demo hard-codes some types but only because adding any marshaling code would hide what is going on.

#include <string>
#include <iostream>

struct State;
typedef std::string (*function_type)(State*);
void registerFunction(std::string const& name, function_type function)
{
    std::cout << "calling '" << name << "': " << function(0) << "\n";
}

template <typename T> class RegisterHelper;

template <typename RC, typename... Args>
class RegisterHelper<RC(Args...)>
{
public:
    template <RC (*function)(Args...)>
    static void doRegister(std::string const& name) {
        registerFunction(name, [](State*) -> std::string {
                return function(17, 4.0);
            });
    }
};

std::string foo(int, double) { return "foo"; }
std::string bar(int, double) { return "bar"; }

int main()
{

    RegisterHelper<decltype(foo)>::doRegister<&foo>("foo");
    RegisterHelper<decltype(bar)>::doRegister<&bar>("bar");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!