C 将功能模板作为参数作为回调
C++ Passing function templates as arguments to other functions as callback
我具有下面的功能:
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上的一个现场示例。
相关文章:
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- C++存储带有可变参数的回调
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 以特征类型作为参数的泛型函数回调
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 模板化回调参数的逆变,如 C# 中的逆变
- 带有参数的嵌入式系统上的最小c++回调
- 如何用不同的参数类型和数字回调函数
- 如何成功地将函数对象(或lambda)传递给trackbar回调的第二个参数(void*)
- v8 源代码中 ArrayMap 函数的回调 fn 参数是什么?
- 如何将提升回调作为参数传递给方法?
- 回调参数中的协方差C++
- sqlite3 更改函数回调参数 void* not用于 int* C++
- 将lambda传递到lambda回调参数
- C++-17变量模板:捕获回调参数的返回类型和参数类型
- 回调参数被转移
- 脚本回调参数和结果的自动编组
- 在继承类中回调参数类型不匹配
- 将回调参数从c#传递到非托管c++
- 将此实例作为回调参数发送