By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,798 Members | 1,766 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,798 IT Pros & Developers. It's quick & easy.

Function/pointer help

P: n/a
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"?
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
QH Hong wrote in news:16**************************@posting.google.c om:
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.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #2

P: n/a
> 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.
{
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;
}

Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.