C 将功能模板作为参数作为回调

C++ Passing function templates as arguments to other functions as callback

本文关键字:回调 参数 功能      更新时间:2023-10-16

我具有下面的功能:

template<typename... Args>
int
error_handler (const char *format, Args&... args)
{
    // deal with the information passed
}

我正在编写一个在开业期间采用此类功能指针的库,因此库可以在发生某些事情时将其作为回调。但是,我无法编写这样的API。我尝试了以下内容,但编译器不喜欢它:

void init(template<typename... Args> int (*error_handler_cb)(const char *format, Args&... args));

这是错误:

error: expected identifier before 'template'
     void init(template<typename... Args> int (*error_logger_cb)(const char *format, Args&... args),
                      ^~~~~~~~
libapi.hpp:20:22: error: expected ',' or '...' before 'template'

有人可以帮助我克服这一点吗?

您不能将类型作为函数参数传递,而只能将一个值传递。您可以通过需要一个函子来利用init的约束:

template<typename F>
void init(F f)
{
    // ...
}

如果您需要存储f以后调用,则可以选择std::function

namespace {
    std::vector<std::function<int(void)>> init_functions;
}
template<typename F>
void init(F f)
{
    init_functions.push_back(f);
}

完整的实现可能是这样的:

namespace {
    std::vector<std::function<int(void)>> init_functions;
}
template<typename... Args>
int
error_handler (const char *format, Args&&... args)
{
    do_something(format);
    do_something(args...);
    return 0;
}
template<typename F>
void init(F f)
{
    init_functions.push_back(f);
}
int main()
{
    auto f = []() {
        return error_handler("test", 4, 2);
    };
    init(f);
    return init_functions[0]();
}

请注意,像您一样,在error_handler中使用RVALUE参考而不是LVALUE参考。这允许通过main函数中的RVALUE。

请参阅Rextester上的一个现场示例。