c++ - 如何在 C/C++ 中将 typedef 函数作为参数传递

标签 c++ c

我在网上查了一段时间,但没有发现任何与我的问题完全相似的内容。我正在使用一个定义了这个东西的类:

typedef bool ProgressCallback(double progress);

然后有一个函数像这样使用它:

// The documentation says that it will call progress_callback()
// during the write where the progress parameter = percentage complete
void WriteToFile(char* filename, ProgressCallback* progress_callback)

我到底应该如何调用这个函数?主要是 typedef 语法让我失望,因为将函数作为参数传递通常并不那么困难。这是我尝试过的:

// Apparently I can't just say "Progress Callback MyCallback{}"
// Since it gives me "function type may not come from a typedef" error
bool MyCallbackFunction(double progress){
    return true;
}

void OtherFunction(){

    // Can't assign. I get "a value type of bool (*)(double progress)" cannot be
    // used to initalize an entity of type ProgressCallback*" error.
    ProgressCallback* myfunction = MyCallbackFunction;
    WriteToFile("Test.txt", myfunction);
}

显然我知道我这样做是错误的。但这是我所得到的最接近的。我完全不知道如何将该参数传递给 WriteToFile()。

任何帮助将不胜感激!

最佳答案

使用

typedef bool (*ProgressCallback)(double progress);

定义ProgressCallback

然后,您可以使用

ProgressCallback myfunction = MyCallbackFunction;
WriteToFile("Test.txt", myfunction);

关于c++ - 如何在 C/C++ 中将 typedef 函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43284213/

相关文章:

c++ - 为什么在调用 std::call_once() 时需要这个指针?

c++ - constexpr vector push_back 或如何 constexpr 所有的东西

c++ - 不同目录上的 ifstream

c++ - 为什么在将 C 样式数组传递给需要 std::string 的方法时出现链接器问题?

c++ - 在 OoOE 处理器中,内存存储真的可以重新排序吗?

用 C 创建自己的 toUpper 和 toLower

c# - 你如何在 C# 中为我的撤消重做类只分配一个指针

c - strncpy 不是比 strcpy 更好吗?

c++ - OpenCV 断言矩阵乘法失败

连续调用递归函数两次