问题描述
我有一个程序,必须将函数存储为 void(*)(void *)
.用该签名创建函数会导致代码重复(通常第一行是将void指针强制转换为正确的类型)并降低了类型安全性(void指针可以强制转换为任何类型,例如错误的类型),所以我想知道如果我可以采用 void(*)(T *)
类型的函数,然后将其转换为 void(*)(void *)
并按如下方式调用它,其方式与此类似:
I have a program that has to store functions as void (*) (void*)
. Creating functions with that signature leads to code duplication (usually the first line is to cast the void pointer to the correct type) and reduces type safety (the void pointer can be cast to anything, such as the wrong type), so I was wondering if I can take a function of type void (*)(T*)
, and then convert it to a void(*)(void*)
and call it like that, in a way similar to this:
#include <iostream>
#include <string>
void printer(std::string* string)
{
std::cout << *string << std::endl;
}
int main()
{
//Cast the function to a one that takes a void pointer
auto func = reinterpret_cast<void(*)(void*)>(&printer);
//Create a string and call the function with it
std::string string = "Hello World";
func(&string);
return 0;
}
上面的代码可以编译并正常运行(在 ideone 上),但我想知道它是否完全符合所有标准或者它是未定义的行为,并且对于我的特定示例和OS来说只能正常工作
The above code compiles and runs fine (on ideone) but I was wondering if it's at all standards compliant or if it's undefined behaviour and is just working correctly for my specific example and OS
推荐答案
这样做的行为是不确定的.标准(草稿)说:
Behaviour of doing so is undefined. Standard (draft) says:
您可以使用lambda:
You could use a lambda:
void(*func)(void*) = [](void *string) {
printer(static_cast<std::string*>(string));
};
这篇关于在函数指针类型之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!