C++ 函数指针中的参数数目可变

C++ 函数指针中的参数数目可变,c++,function-pointers,managed-c++,C++,Function Pointers,Managed C++,我有一个指向函数的指针,可以指向带有一个、两个或多个参数的函数 double (*calculate)(int); double plus(int a, int b){ return a+b; } double sin(int a){ return Math::Sin(a); } 我怎么可能使用 calculate = plus; calculate = sin; 在同一个节目中。不允许更改函数plus和sin。在管理C++中编写; 我试过double(*calculate)(…)但这

我有一个指向函数的指针,可以指向带有一个、两个或多个参数的函数

double (*calculate)(int);

double plus(int a, int b){ return a+b; }

double sin(int a){ return Math::Sin(a); }
我怎么可能使用

calculate = plus; 
calculate = sin;
在同一个节目中。不允许更改函数plus和sin。在管理C++中编写;
我试过
double(*calculate)(…)
但这不起作用。

plus
赋值给
计算
是一种类型冲突,以后调用
计算
时会导致,因此任何(不好的)情况都可能发生


您可能对(但我不知道它是否适用于托管C++)感兴趣。

您可以尝试使用以下内容:

struct data
{
  typedef double (*one_type) ( int a );
  typedef double (*other_type) ( int a, int b );

  data& operator = ( const one_type& one ) 
  {
    d.one = one;
    t = ONE_PAR;
    return *this;
  }

  data& operator = ( const other_type& two ) 
  {
    d.two = two;
    t = TWO_PAR;
    return *this;
  }

  double operator() ( int a )
  {
    assert( t == ONE_PAR );
    return d.one( a );
  }

  double operator() ( int a, int b )
  {
    assert( t == TWO_PAR );
    return d.two( a, b );
  }

  union func
  {
    one_type one;
    other_type two;
  } d;


  enum type
  {
    ONE_PAR,
    TWO_PAR
  } t;
};
double va( int a ) 
{
  cout << "one\n";
}
double vb( int a, int b ) 
{
  cout << "two\n";
}

这已经在这里被问到和回答了:它传输args的数量,这在我的算法中是不可能的。我想做一个函数重载。不幸的是,它不是在托管C++中工作。
data d;
d = va;
d( 1 );
d = vb;
d( 1, 2 );