2

I've a pointer to the function that can point to the function with one, two or more args.

double (*calculate)(int);

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

double sin(int a){ return Math::Sin(a); }

how is it possible for me to use

calculate = plus; 
calculate = sin;

in the same program. Not allowed to change functions plus and sin. Writing in managed c++;

I've tried double (*calculate)(...); but that's not working.

Shoe
  • 74,840
  • 36
  • 166
  • 272
a3dsfcv
  • 1,146
  • 2
  • 20
  • 35

2 Answers2

0

The assignment of plus to calculate is a type violation, and when calling calculate later leads to undefined behavior, so anything (bad) can happen.

You might be interested in libffi (but I have no idea if it works with managed C++).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

You can try use something like this:

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";
}

This works fine:

data d;
d = va;
d( 1 );
d = vb;
d( 1, 2 );
Pavel Davydov
  • 3,379
  • 3
  • 28
  • 41