在函数指针类型之间转换

奥尔比

我有一个程序必须将功能存储为void (*) (void*)创建具有该签名的函数会导致代码重复(通常第一行是将void指针强制转换为正确的类型)并降低了类型安全性(void指针可以强制转换为任何类型,例如错误的类型),所以我想知道如果我可以采用type函数void (*)(T*),然后将其转换为avoid(*)(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上),但是我想知道它是否符合所有标准,或者它是否是未定义的行为,并且对于我的特定示例和操作系统是否正常工作

埃雷里卡

这样做的行为是不确定的。标准(草稿)说:

[expr.reinterpret.cast]函数指针可以显式转换为其他类型的函数指针。[注意:通过指向与函数定义中使用的类型不同的函数类型(9.2.3.5)的指针调用函数的效果是不确定的。—尾注]除了将“ pointer to T1”类型的prvalue转换为“ pointer to T2”类型(其中T1和T2是函数类型)并返回其原始类型以外,都会产生原始指针值,这样的结果指针转换未指定。[注意:有关指针转换的更多详细信息,请参见7.3.11。—尾注]


您可以使用lambda:

void(*func)(void*) = [](void *string) {
    printer(static_cast<std::string*>(string));
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章