c++ - 通过函数指针传递给可变参数函数的参数改变它们的值

标签 c++ c++11 function-pointers

我有一个包含一些静态函数的类和一个包含指向这些函数的指针的映射:

class Conditions
{
    using cbType = bool(*)();
    static std::unordered_map<std::string, cbType> const m_FunctionMap;

    static bool Equal_int(const int A, const int B) { return A == B; }
    static bool Equal_float(const float A, const float B) { return A == B; }
    static bool Greater_int(const int A, const int B) { return A > B; }
    static bool Greater_float(const float A, const float B) { return A > B; }
    static bool Between_int(const int A, const int B, const int C) { return A > B && A < C; }
    static bool Between_float(const float A, const float B, const float C) { return A > B && A < C; }
};

因此,静态函数可以有不同数量和不同类型的参数。在 .cpp 文件中,我正在初始化该 map :

std::unordered_map<std::string, Conditions::cbType> const Conditions::m_FunctionMap
{
    { "Equal_int", MakeMapVal(&Equal_int) },
    { "Equal_float", MakeMapVal(&Equal_float) },
    { "Greater_int", MakeMapVal(&Greater_int) },
    { "Greater_float", MakeMapVal(&Greater_int) },
    { "Between_int", MakeMapVal(&Between_int) },
    { "Between_float", MakeMapVal(&Between_float) },
};

然后我在类 Conditions 中添加了一个方法来通过它们的名称调用这些静态函数:

    template <typename ... argsType>
    static bool Call(std::string const& Key, argsType&& ... Args)
    {
        using prototype = bool(*)(argsType ...);
        return reinterpret_cast<prototype>(m_FunctionMap.at(Key))(Args ...);
        //return reinterpret_cast<prototype>(m_FunctionMap.at(Key))(std::forward<argsType>(Args) ...);  // this has the same issue
    }

现在,当我运行这段代码时,调用正确调用相应静态函数的 Call(std::string const& Key, argsType&& ... Args) 方法。例如:

Call("Greater_int", 42, 40);

但是,在 Greater_int() 函数中,这两个参数不再是 42 和 40,而是一些随机值。但在 Call 函数中,这些值正确地为 4240。因此,当通过 reinterpret_cast 调用函数指针时,这些值会发生变化。

知道我在这里做错了什么吗?

最佳答案

您处于未定义行为的荒野中。您的 reinterpret_cast 是从不相关的类型进行转换的,这很糟糕。删除强制转换并以其他方式让编译器满意。

关于c++ - 通过函数指针传递给可变参数函数的参数改变它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41187051/

相关文章:

c++ - 嵌入式状态机申请什么设计

c - 如何区分C中的函数指针是指向函数1还是函数2

c - 函数指针存放在哪里?

c++ - T*... 和 const T& 的部分排序

c++ - 从 'char' 到 'const char *' 的无效转换

c++ - 在 Intellij 的 CLion 结构面板中显示类名

c++ - 当 T 没有复制构造函数时,std::queue<T> 的虚拟包装器不编译

c++ - 如何正确公开基础模板类型以用作类型

c - 如何将参数传递给 C 中的函数指针?

c++ - range-v3 views::drop和views::drop_exactly有什么区别?