[英]How to cast from double(*)(void) to a function pointer with given number of parameter?
I have a function pointer with with type double(*)(void)
and I want to cast it to a function with given number parameter. 我有一个带有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;
I can ensure that the cast is correct, is any way to do the cast without if-else? 我可以确保强制转换正确,是否可以通过if-else进行强制转换?
Premise that is a very unsafe way to play with pointers, you can do it with reinterpret_cast
. 前提条件是使用指针进行播放非常不安全的方式,您可以使用reinterpret_cast
。
This is a complete example: 这是一个完整的示例:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.