我有一个程序必须将函数存储为
上述代码在ideone上编译并运行正常,但我想知道它是否符合标准,或者它是否是未定义的行为,并且只对我的特定示例和操作系统正常工作。
void (*) (void*)
。创建具有该签名的函数会导致代码重复(通常第一行是将void指针转换为正确的类型),并减少类型安全性(void指针可以被转换为任何内容,例如错误的类型)。因此,我想知道是否可以将类型为void (*)(T*)
的函数转换为void(*)(void*)
,并以类似以下方式调用它:#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上编译并运行正常,但我想知道它是否符合标准,或者它是否是未定义的行为,并且只对我的特定示例和操作系统正常工作。
[&print](void* value) {...}
),但是捕获会使其“有状态”,现在它无法转换为函数指针。 - Andriy Tylychkoprinter
在这里是命名空间成员而不是函数局部变量,所以 lambda 捕获并不适用于它。 - aschepler