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.

2
  • 2
    This was already asked and answered here: stackoverflow.com/q/11037393/2036917 Commented Apr 2, 2013 at 11:13
  • it transfers num of args, it's not possible in my algo. I wanna make a kind of function overloading. Commented Apr 2, 2013 at 12:51

2 Answers 2

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++).

Sign up to request clarification or add additional context in comments.

Comments

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 );

1 Comment

unfortunately, isnt working in managed c++

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.