Function/pointer help

Q

QH Hong

Compilation of the folowing program gives error message

error C2664: 'solve' : cannot convert parameter 1
from 'double (double)' to 'double (__cdecl *)(double)'

Here's the codes

==== class definition ========
#include "tCls.h"

tCls::tCls()
{
}

tCls::~tCls()
{
}

double tCls::comp1(double x)
{
return x + 1;
}

======== main function =======
typedef double (*function) (double x);

double func1(double x)
{
return x + 2.0;
}

double solve (function f, double x)
{
return f(x) + 3.0;
}

int main(int argc, char* argv[])
{
tCls a;
double t;
t = solve(func1, 1.0);
t = solve(a.comp1, 2.0);
return 0;
}
===============================

How should I define the "function"?
 
R

Rob Williscroft

QH Hong wrote in
How should I define the "function"?

You tried (using an invalid expression a.member_fuction_name) to
convert a member function to a non-member (aka free/global/regular)
function, the language doesen't provide any way of doing this.

The folowing may help solve your problem using a "Functor".

#include <iostream>
#include <ostream>

/* Simple Functor
*/
struct tCls
{
double operator () ( double x ) const
{
return x + 3.145926;
}
};

/* A regular function is also a Functor
*/
double func1(double x)
{
return x + 2.0;
}

template < typename function >
double solve (function f, double x)
{
return f(x) + 3.0;
}

int main()
{
tCls a;
std::cout << solve(func1, 1.0) << "\n";
std::cout << solve( a, 2.0) << std::endl;
}

HTH.

Rob.
 
C

Chris Mantoulidis

double solve (function f, double x)
^^^^^^^^

I believe this is the problem... I think "function" is some kinda
special thingy for C++... At least, if I rename "function" to "f1",
the program will compile OK.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,405
Latest member
DavidCex

Latest Threads

Top