2016-09-10 8 views
2

私はタイプがdouble(*)(void)の関数ポインタを持っており、与えられた数値パラメータを持つ関数にそれをキャストしたいと思います。double(*)(void)から指定されたパラメータ数の関数ポインタにキャストする方法はありますか?

// 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なしでキャストを行う方法はありますか?

+1

短い答えは:なし。 –

+0

答えはタイプBTWの場合と同じになります。 –

+0

'switch 'を提供できますか? –

答えて

0

前提はポインタで遊ぶのが非常に危険な方法です。 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; 
} 
関連する問題