我有一个带有这个签名的模板成员函数:
template<typename T> void sync(void (*work)(T*), T context);
可以使用指向接受类型参数的函数的指针来调用它T*。context传递给该函数。实现是这样的:
template<typename T> void queue::sync(void (*work)(T*), T context) {
dispatch_sync_f(_c_queue, static_cast<void*>(&context),
reinterpret_cast<dispatch_function_t>(work));
}
它使用reinterpret_cast<>并且有效。问题是标准没有很好地定义它,而且非常危险。我怎样才能摆脱这个?我试过static_cast了,但这给了我一个编译器错误:
static_castfromvoid (*)(std::__1::basic_string<char> *)todispatch_function_t(akavoid (*)(void *)) 是不允许的。
dispatch_function_t是 C 类型,与void (*)(void*).
我不确定我是否足够清楚。它的作用是dispatch_sync_f调用给定的回调函数并将给定的上下文参数传递给该回调函数。(它在另一个线程上执行此操作,尽管这超出了此问题的范围。)