[英]How to replace a function pointer with a template parameter or a std::function?
我在visualstudio中运行了一个sonarlint插件。 我的代码有一个主要问题,如下所示:
_declspec(dllexport) void GetInformation(void (add)(const char* pCarName))
{
add("N3-988");
add("N3-40");
add("N3-41");
add("N3-428");
}
错误是
cpp:S5205 : Replace this function pointer with a template parameter or a "std::function".
如何解决?
错误是一个红鲱鱼。 您打错了 function 指针语法,仅此而已。 你需要
void (*add)(const char* pCarName)
作为参数类型。 然后add
是一个 function 指针,它在 function 主体( add("N3-988");
等)中的使用是合适的。
这不是一个真正的错误,从某种意义上说,您不能使用 function 指针作为参数。 你可以。 出于模糊、灵活性和性能原因,不鼓励使用 function 指针。 请参阅https://jira.sonarsource.com/browse/RSPEC-5205 。 因此,如果您不关心这些考虑因素,您可能想要抑制它。
缺乏灵活性意味着您不能传递额外的上下文(除非使用所谓的“thunk”)。 这种缺乏灵活性可以通过对用户上下文使用额外的void*
参数来解决:
_declspec(dllexport) void GetInformation(
void (add)(const char* pCarName, void* context), void* context)
{
add("N3-988", context);
add("N3-40", context);
add("N3-41", context);
add("N3-428", context);
}
You can also used std::function
, as suggested, if you don't ming that your DLL will have C++ interface (so will depend on C++ runtime):
_declspec(dllexport) void GetInformation(std::function<void (const char*)> add)
{
add("N3-988");
add("N3-40");
add("N3-41");
add("N3-428");
}
请注意,您不能按照建议使用template
,因为无法使用__declspec(dllexport)
从 DLL 导出模板。 由于避免间接,模板将具有固定的性能,但 DLL 接口意味着您无法避免它。
注意function作为参数:
void GetInformation(void (add)(const char* pCarName))
由于所谓的衰减,相当于 function 指针参数:
void GetInformation(void (*add)(const char* pCarName))
建议用另一个替换一个的答案具有误导性,它不会解决任何问题。
也许类似于以下内容
#include <cstdio>
template<typename FuncT>
void GetInformation(FuncT func)
{
func("N3-988");
func("N3-40");
func("N3-41");
func("N3-428");
}
int main()
{
auto func = [](const char* s){ printf("%s\n",s); };
GetInformation(func);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.