我有一个类型为double(*)(void)的函数指针,我想将其转换为具有给定number参数的函数。

// already have function my_func with type double(*)(void)
int para_num;
para_num = get_fun_para_num(); // para_num can be 1 or 2

if para_num == 1
    cout << static_cast<double (*)(double)>(my_func)(5.0) << endl;
else
    cout << static_cast<double (*)(double, double)>(my_func)(5.0, 3.1) << endl;

我可以确保强制转换正确,是否可以通过if-else进行强制转换?

最佳答案

前提是使用指针玩耍是非常不安全的方式,
您可以使用 reinterpret_cast 来完成。

这是一个完整的示例:

#include <iostream>

/// A "generic" function pointer.
typedef void* (*PF_Generic)(void*);

/// Function pointer double(*)(double,double).
typedef double (*PF_2Arg)(double, double);

/// A simple function
double sum_double(double d1, double d2) { return d1 + d2; }

/// Return a pointer to simple function in generic form
PF_Generic get_ptr_function() {
  return reinterpret_cast<PF_Generic>(sum_double);
}

int main(int argc, char *argv[]) {
  // Get pointer to function in the "generic form"
  PF_Generic p = get_ptr_function();

  // Cast the generic pointer into the right form
  PF_2Arg p_casted = reinterpret_cast<PF_2Arg>(p);

  // Use the pointer
  std::cout << (*p_casted)(12.0, 18.0) << '\n';

  return 0;
}

关于c++ - 如何从double(*)(void)转换为具有给定数量参数的函数指针?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39425982/

10-11 22:39
查看更多