Pointer to function member and non-member - c++

Abstract
I have a class that stores a optimization problem and runs a solver on that problem.
If the solver fails I want to consider a sub-problem and solve using the same solver (and class).
Introduction
An optimization problem is essencially a lot of (mathematical) functions. The problem functions are defined outside the class, but the sub-problem functions are defined inside the class, so they have different types (e.g. void (*) and void (MyClass::*).
At first I thought that I could cast the member function to the non-member pointer-to-function type, but I found out that I cannot. So I'm searching for some other way.
Example Code
An example code to simulate my issue:
#include <iostream>
using namespace std;
typedef void (*ftype) (int, double);
// Suppose foo is from another file. Can't change the definition
void foo (int n, double x) {
cout << "foo: " << n*x << endl;
}
class TheClass {
private:
double value;
ftype m_function;
void print (int n, double x) {
m_function(size*n, value*x);
}
public:
static int size;
TheClass () : value(1.2), m_function(0) { size++; }
void set_function (ftype p) { m_function = p; }
void call_function() {
if (m_function) m_function(size, value);
}
void call_ok_function() {
TheClass ok_class;
ok_class.set_function(foo);
ok_class.call_function();
}
void call_nasty_function() {
TheClass nasty_class;
// nasty_class.set_function(print);
// nasty_class.set_function(&TheClass::print);
nasty_class.call_function();
}
};
int TheClass::size = 0;
int main () {
TheClass one_class;
one_class.set_function(foo);
one_class.call_function();
one_class.call_ok_function();
one_class.call_nasty_function();
}
As the example suggests, the member function can't be static. Also, I can't redefine the original problem function to receive an object.
Thanks for any help.
Edit
I forgot to mention. I tried changing to std::function, but my original function has more than 10 arguments (It is a Fortran subroutine).
Solution
I made the change to std::function and std::bind as suggested, but did not went for the redesign of a function with more 10 arguments. I decided to create an intermediate function. The following code illustrates what I did, but with fewer variables. Thanks to all.
#include <iostream>
#include <boost/tr1/functional.hpp>
using namespace std;
class TheClass;
typedef tr1::function<void(int *, double *, double *, double *)> ftype;
// Suppose foo is from another file. Can't change the definition
void foo (int n, int m, double *A, double *x, double *b) {
// Performs matrix vector multiplication x = A*b, where
// A is m x n
}
void foo_wrapper (int DIM[], double *A, double *x, double *b) {
foo(DIM[0], DIM[1], A, x, b);
}
class TheClass {
private:
ftype m_function;
void my_function (int DIM[], double *A, double *x, double *b) {
// Change something before performing MV mult.
m_function(DIM, A, x, b);
}
public:
void set_function (ftype p) { m_function = p; }
void call_function() {
int DIM[2] = {2,2};
if (m_function) m_function(DIM, 0, 0, 0);
}
void call_nasty_function() {
TheClass nasty_class;
ftype f = tr1::bind(&TheClass::my_function, this, _1, _2, _3, _4);
nasty_class.set_function(f);
nasty_class.call_function();
}
};
int main () {
TheClass one_class;
one_class.set_function(foo_wrapper);
one_class.call_function();
one_class.call_nasty_function();
}
PS. Creating a std::function with more than 10 variables seemed possible (compiled, but I didn't test) with
#define BOOST_FUNCTION_NUM_ARGS 15
#include <boost/function/detail/maybe_include.hpp>
#undef BOOST_FUNCTION_NUM_ARGS
But creating a std::bind for more than 10 arguments does not seem as easy.

std::function, std::bind, and lambdas are what you are looking for. In short, function pointers are very bad things and should be burned in fire. In long, std::function can store any function object which can be called with the correct signature, and you can use std::bind or a lambda to generate a function object that calls your member function quickly and easily.
Edit: Then you will just have to roll your own std::function equivalent that supports more than 10 arguments.

Related

C++ member function pointer to global function pointer

I have to solve, at least for me, a tricky problem in C++. There is a dll which i can not modify. It gets a function pointer as argument. If I pass a pointer to a global function everything works fine. Unfortunatelly there is a list of same class objects to pass to the dll. In C# I solved this by using delegates. How can this be done in C++? Using std::function does not work. With that there are coding convention errors during runtime. Further using MSVC2010 would be optimal.
I wrote a sample which describes the problem:
#include <stdio.h>
// global function which works
void __stdcall task_global(float x, float y) { printf("Called global function with: %f %f\n", x, y); }
typedef void(__stdcall *f_pointer)(float, float);
// try of using a member function
class BaseTask {
public:
virtual void __stdcall task(float x, float y) = 0;
};
class ListeningTask :public BaseTask {
public:
void __stdcall task(float x, float y) { printf("Called this member function with: %f %f\n", x, y); }
};
typedef void (BaseTask::*member_f_pointer)(float, float);
// the dll to use
class RegisterTask {
public:
// no posibility to access or modify!
void __stdcall subscribe(f_pointer fp) { fp(1.0f, 2.0f); }
// just for demonstration how to use a member function pointer
void __stdcall subscribeMemberDemo(member_f_pointer mfp) { /*how to use mfp?*/};
};
int main() {
RegisterTask register_task{};
// use global function
f_pointer pointer_to_global_task = task_global;
register_task.subscribe(pointer_to_global_task);
/*---------------------------------------------------------------*/
// use member function?
std::list<ListeningTask> listening_task_list;
for(int i = 0; i < 10; i++) {
listening_task_list.push_back(ListeningTask lt);
member_f_pointer pointer_to_member_task = &listening_task_list.back().task; //error C2276: '&': illegal operation on bound member function expression
register_task.subscribeMemberDemo(pointer_to_member_task);
// the tricky and important one to solve
// how to pass the member function to this subscribe(f_pointer)?
register_task.subscribe(pointer_to_member_task);
}
getchar();
return 0;
}
The important question is how to pass a member function pointer to the RegisterTask::subscribe(f_pointer)?
The parenthetic question is how to pass a member function to the RegisterTask::subscribeMemberDemo(member_f_pointer)?
I hope someone can help me to solve this? I am working on this since days.
Edit:
I modified the question to emphasize the problem with the list of ListenerTask. How to pass a member function pointer is now clear to me through the answers of #pokey909 and #AndyG. Both of them provide a pointer to one object or rather a list of objects. If the callback is called the one ListenerTask or all std::list<*ListenerTask> are called at once. But how to let only one ListenerTask of the list to be called. Passing more than one callback to the dll. It (RegisterTask) can do that, because the following example with global functions works.
void __stdcall task_global_1(float x, float y) { printf("Called global function 1 with: %f %f\n", x, y); }
void __stdcall task_global_2(float x, float y) { printf("Called global function 2 with: %f %f\n", x, y); }
void __stdcall task_global_3(float x, float y) { printf("Called global function 3 with: %f %f\n", x, y); }
typedef void(__stdcall *f_pointer)(float, float);
int main() {
// give the functions to the dll.
f_pointer pointer_to_global_task_1 = task_global_1;
register_task.subscribe(pointer_to_global_task_1);
f_pointer pointer_to_global_task_2 = task_global_2;
register_task.subscribe(pointer_to_global_task_2);
f_pointer pointer_to_global_task_3 = task_global_3;
register_task.subscribe(pointer_to_global_task_3);
}
There are three global function pointers. They are all given to the dll. Now, if the dll has a task for task_global_2 it notifies this only! How to achive this distinction with member function pointer?
Note:
I got the source of the dll. Hope this helps. Unfortunately modifying, building is not possible. Here is the callback definition:
type TCallback = procedure( x : single; y : single; ); stdcall;
procedure subscribe(aCallback: TCallback ); StdCall;
begin
TaskSocket.addTask( aCallback );
end;
procedure TSocket.addTask( aCallback : TCallback);
var newTask : TTask;
begin
newTask := TTask.Create(aCallback);
TaskList.addItem(newTask);
end;
You can use a freestanding function that calls a wrapper which binds your instance to it.
Here is rough example
#include <iostream>
#include <string>
#include <functional>
// global function which works
std::function<void(float, float)> memberCb;
void task_global(float x, float y) { memberCb(x, y); }
typedef void(*f_pointer)(float, float);
// try of using a member function
class BaseTask {
public:
virtual void task(float x, float y) = 0;
};
class ListeningTask :public BaseTask {
public:
void task(float x, float y) { printf("Called this member function with: %f %f\n", x, y); }
};
typedef void (BaseTask::*member_f_pointer)(float, float);
void callbackWrapper(BaseTask* t, float x, float y) { t->task(x, y); }
// the dll to use
class RegisterTask {
public:
// no posibility to access or modify!
void subscribe(f_pointer fp) {
fp(1.0f, 2.0f);
}
// just for demonstration how to use a member function pointer
void subscribeMemberDemo(member_f_pointer mfp) { /*???*/ };
};
int main() {
RegisterTask register_task{};
ListeningTask listening_task{};
memberCb = std::bind(&callbackWrapper, &listening_task, std::placeholders::_1, std::placeholders::_2);
register_task.subscribe(task_global);
return 0;
}
Note
Based on the comment, I'm not sure if all of this works in MSVC2010, since I don't have this compiler version. But rudimentary C++11 support should be in there.
Edit
I'm not sure if thats what you are after, but would this solve your problem?
void callbackWrapper(const std::list<BaseTask*> &taskList, float x, float y) {
for (auto t : taskList)
t->task(x, y);
}
int main() {
RegisterTask register_task{};
std::list<BaseTask*> taskList;
for (int i = 0; i < 4; ++i)
taskList.push_back(new ListeningTask);
memberCb = std::bind(&callbackWrapper, taskList, std::placeholders::_1, std::placeholders::_2);
register_task.subscribe(task_global);
return 0;
}
Edit 2
Ok I think I got what you want. The best I can come up with without splattering your code with global functions manually is with template magic.
Note however, that it is not as flexible as you might want because you have to bind those methods at compile time.
If you need to add them at runtime, you can probably use the same trick but without templates. Simply put all the std::function objects in a vector and wrap that up in a singleton or something similar.
#include <iostream>
#include <string>
#include <functional>
#include <list>
/* Simulated DLL */
typedef void(*f_pointer)(float, float);
class RegisterTask {
public:
void subscribe(f_pointer fp) {
fp(1.0f, 2.0f);
}
};
/* Static function generator to ease the pain to define all of them manually */
template<unsigned int T>
std::function<void(float, float)> &getWrapper() {
static std::function<void(float, float)> fnc;
return fnc;
}
/* Same here */
template<unsigned int T>
void task_global(float x, float y) { getWrapper<T>()(x, y); }
class BaseTask {
public:
virtual void task(float x, float y) = 0;
};
class ListeningTask :public BaseTask {
public:
ListeningTask(int taskNum) : m_taskNum(taskNum) {}
void task(float x, float y) { printf("Called this member of task %d function with: %f %f\n", getTaskNum(), x, y); }
int getTaskNum() const { return m_taskNum; }
private:
int m_taskNum;
};
/* Context injector */
void callbackWrapper(BaseTask* t, float x, float y) {
t->task(x, y);
}
/* Convenience function to bind an instance to a task */
template<unsigned int T>
void bindTask(ListeningTask* t) {
getWrapper<T>() = std::bind(&callbackWrapper, t, std::placeholders::_1, std::placeholders::_2);
}
int main() {
RegisterTask register_task{};
auto task0 = new ListeningTask(1337);
auto task1 = new ListeningTask(1984);
auto task2 = new ListeningTask(42);
bindTask<0>(task0);
register_task.subscribe(task_global<0>);
bindTask<1>(task1);
register_task.subscribe(task_global<1>);
bindTask<2>(task2);
register_task.subscribe(task_global<2>);
return 0;
}
Run Code demo
pokey909's answer is totally great, but if you don't even have access to std::function and std::bind, we can hack our way around it.
The gist of the approach is that we are going to define a template class with an implicit conversion to the desired function type. The downside is that each new additional wrapper requires a new type declaration.
// assumes two function arguments
template<class Ret, class Mem, class Arg1, class Arg2, int>
struct MemBind
{
typedef Ret(Mem::*mem_fn_type)(Arg1, Arg2);
static void Set(mem_fn_type _fn, Mem* _instance)
{
fn = _fn;
instance = _instance;
}
static Ret DoTheThing(Arg1 first, Arg2 second)
{
return ((*instance).*fn)(first, second);
}
typedef Ret(*fn_type)(Arg1, Arg2);
operator fn_type ()
{
return DoTheThing;
}
static mem_fn_type fn;
static Mem* instance;
};
Given some struct Foo with our desired callback:
struct Foo
{
void Bar(float a, float b)
{
std::cout << "Foo::Bar(float, float) " << a << " , " << b << std::endl;
}
};
We have to define our static members:
typedef MemBind<void, Foo, float, float, 0> MemBindZero;
template<> Foo* MemBindZero::instance = nullptr;
template<> void(Foo::*MemBindZero::fn)(float, float) = nullptr;
We can have a caller that takes in a function pointer:
void Caller(void(*_fn)(float, float))
{
_fn(42.0, 1337.0);
}
The key here is that MemBind has an implicit conversion to the desired function type. The 0 in the typedef for MemBindZero allows us to re-use the same types for the other arguments, but increment the counter to 1 when used. I think you could probably replace it with a __COUNTER__ macro or something like that, but it would be nonstandard so I did it manually.
Now the next bit is to create an instance of MemBindZero, then set the static members, and finally pass our instance into Caller:
Foo f;
MemBindZero bound;
bound.Set(&Foo::Bar, &f);
Caller(bound);
Demo
In the demo I wrapped the static member initialization into a more convenient macro:
#define MEMBIND(RET, CLASS, ARG1, ARG2, COUNT, ALIAS) \
typedef MemBind<RET, CLASS, ARG1, ARG2, COUNT> ALIAS; \
template<> CLASS * ALIAS::instance = nullptr; \
template<> RET(CLASS::*ALIAS::fn)(ARG1, ARG2) = nullptr;
So that I could call it like so:
MEMBIND(void, Foo, float, float, 0, MemBindZero)
MEMBIND(void, OtherFoo, float, float, 1, MemBindOne)

Why does this boost bind non-static member function fail? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Why does the following compiles i.e. passing a free function as parameter with the right signature:
inline double free_adapter_f(unsigned n, const double *x, double *grad, void *d) {
return 0.0;
}
nlopt::opt opt(nlopt::LN_NELDERMEAD, X.size());
opt.set_min_objective(free_adapter_f, NULL);
whereas this other doesn't compile i.e. passing the result of boost::bind a class member function with the same signature:
template<class Space, class Solution, class Oracle>
inline double NelderMead<Space, Solution, Oracle>::adapter_f(unsigned n, const double *x, double *grad, void *d) {
return 0.0;
}
nlopt::opt opt(nlopt::LN_NELDERMEAD, X.size());
opt.set_min_objective(boost::bind(&NelderMead::adapter_f, this, ::_1, ::_2, ::_3, ::_4), NULL);
The error message is the following:
nelder_mead.h(98): error: no instance of overloaded function "nlopt::opt::set_min_objective" matches the argument list
argument types are: (boost::_bi::bind_t<double, boost::_mfi::mf4<double, NelderMead<TestSpace, VectorXd, oracle_f>, unsigned int, const double *, double *, void *>, boost::_bi::list5<boost::_bi::value<NelderMead<TestSpace, VectorXd, oracle_f> *>, boost::arg<1>, boost::arg<2>, boost::arg<3>, boost::arg<4>>>, long)
object type is: nlopt::opt
opt.set_min_objective(boost::bind(&NelderMead::adapter_f, this, ::_1, ::_2, ::_3, ::_4), NULL);
UPDATE: the overloaded set_min_objective are:
typedef double (*func)(unsigned n, const double *x, double *grad, void *f_data);
typedef double (*vfunc)(const std::vector<double> &x, std::vector<double> &grad, void *f_data);
void set_min_objective(func f, void *f_data);
void set_min_objective(vfunc vf, void *f_data);
You need to define set_min_objective which accepts boost::function as first parameter:
typedef boost::function<double (unsigned n, const double *x, double *grad, void *f_data)> func_t;
...
void set_min_objective(func_t, void*);
...
another thing - you'd better not to use NULL
Here is a simple example, which demonstrates your problem:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
namespace g
{
typedef int (*func)(int a, int b, int c);
void bar(func f)
{
std::cout << "g::bar:: called" << (*f)(10, 20, 30) << std::endl;
}
// Disable the over load below and you will get the same error
void bar(boost::function<int(int, int, int)> f)
{
std::cout << "g::bar:: called" << f(10, 20, 30) << std::endl;
}
}
template <typename A, typename B, typename C>
class foo
{
public:
int bar(int a, int b, int c) const
{ return a + b + c; }
void call()
{
g::bar(boost::bind(&foo::bar, this, ::_1, ::_2, ::_3));
}
};
int main(void)
{
foo<int, double, int> f;
f.call();
return 0;
}
Main reason is that boost::function<> is not convertible to a function pointer, so you need to provide an overload which accepts this (as above.)
EDIT: just to clarify things a little further. boost::bind() does not explicitly return a boost::function<>, however, the object it returns can be stored in the correct instantiation of boost::function<>, in the above case, the correct instantiation is boost::function<int(int, int, int)>.
Normally you would only need to resort to storing it in a boost::function if you were interested in propagating it (without a template) or storing it for later use. In this case, as you are passing the result of the bind(), you need to have the correct overload to accept the returned object from boost::bind(), and the easiest way to do this without resorting to templates is to accept a boost::function (as above.)
Normally, I'm pragmatic, so I would resort to this (without knowing what you are wanting to do with f) where possible.
template <typename F>
double set_min_objective(F f, ...)
{
}
Then you are agnostic, of course purists will have other opinions.
NOTE: A nice thing with boost::function<> is that you can store a non-member function pointer in one too (as long as the signature matches.) So in reality you only need a version of your function which accepts the correct boost::function<> and it will work in both cases (member function with boost::bind() and non-member function.)
EDIT2: Okay, given the additional information, you have to resort to the following mechanism, you need to have a non-member function of your class, which will then delegate to the member function, for example:
<>
class NelderMead
{
static double delegate_f(unsigned n, const double *x, double *grad, void *f_data)
{
// I'm assuming here the frame work passed you whatever you gave in f_data
NelderMead* inst = reinterpret_cast<NelderMead*>(f_data);
return inst->adapter_f(n, x, grad);
}
double adapter_f(unsigned n, const double *x, double *grad)
{
}
void set()
{
nlopt::opt opt(nlopt::LN_NELDERMEAD, X.size());
opt.set_min_objective(delegate_f, this); //<-- here pass the instance as the additional data
}
};
This is a typical pattern employed by third-party libraries which are meant to be agnostic to user code.
Both overloads of set_min_objective expect a pointer-to-function as the first parameter, but the object returned by boost::bind is not a pointer-to-function, it's a function object.
boost::bind returns a function object that stores the target function and any bound arguments, it doesn't synthesize a function and return a pointer to it, or magically turn a pointer-to-member-function into a pointer-to-function. That would be magic.

Output dynamic array from a function pointer

I'm very new to pointers so please bear with me...
My code defines a function for the multiplication of two matrices (matrixMultiplication). I have then defined a function pointer to this function.
#include <iostream>
void matrixMultiplication (const double A[3][3], const double B[3][3], double output[3][3])
{
int i, j, k;
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
output[i][j]+=A[i][k]*B[k][j];
}
}
}
}
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
double output[3][3];
matrixMultiplication(left, right, output);
}
int main ()
{
using namespace std;
double A[3][3]={{1,1,1},{1,1,1},{1,1,1}};
double B[3][3]={{1,1,1},{1,1,1},{1,1,1}};
cout<<"The function returns..."<<endl;
double print[3][3]=matrixMultiplication(A,B);
int i, j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
cout<<print[i][j]<<"\t";
}
cout<<"\n";
}
return 0;
}
What I want to do is output the array given by the pointer function, *matrixMultiplication, using a for loop (just for aesthetic purposes). I have played around with the code and ended up with initialiser or segmentation (11) errors. I feel like I'm missing something blatantly obvious given I'm new to C++...
Any ideas would be most welcome!
The problem is with:
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
double output[3][3];
matrixMultiplication(left, right, output);
}
I don't know what it is and neither does my compiler! ;)
Using functional, a matrixMultiplication function type can be defined and used, like so:
#include <functional> // or <tr1/functional>
// type
typedef function<void (const double[3][3], const double[3][3], double[3][3])> MatrixFunction;
// instance
MatrixFunction matrixFunctionPtr(&matrixMultiplication);
// call
matrixFunctionPtr(A,B,print);
Note: you also need to declare your output array double print[3][3]; * before* you call the matrixMultiplication function...
You have a function:
void matrixMultiplication (const double A[3][3], const double B[3][3], double output[3][3])
{
...
}
This function works. It takes three arrays as arguments (which is to say it takes three pointers-- this is a subtle point, and I don't think it's a good exercise for a beginner because it clouds the distinction between passing by value and passing by reference -- but never mind that for now) and returns void (i.e. nothing), and . Now you want to construct a function pointer that points to this function. But this:
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
...
}
is not a function pointer; it's a function that returns a pointer to an array of double, but it has some internal errors (and don't even worry about what it takes as arguments for now).
Let's do a simpler example first:
double foo(int n) // function
{
return(3);
}
int main()
{
double (*bar)(int); // function pointer
bar = &foo;
double z = (*bar)(5);
cout << z << endl;
return(0);
}
Now that we see how function pointers work, we apply one to matrixMultiplication:
void (*matFP)(const double A[3][3], const double B[3][3], double output[3][3]);
matFP = &matrixMultiplication;
double C[3][3];
(*matFP)(A,B,C);

Reference to member function

first of all I know that this is not possible in C++. But I hope someone can tell be a workaround for my problem. I have a class which represents a mathematical function:
class myClass:
{
private:
public:
myClass() {};
double value(double, double){ /* doing some complicated calculation here */} };
double integrate { /*calc*/ return integral; };
}
In integrate() I want to create a struct with a reference to value(). The struct is defined as follows:
struct gsl_monte_function_struct {
double (*f)(double * x_array, size_t dim, void * params);
size_t dim;
void * params;
};
(I need this struct to call the Monte-Carlo integration routines from GSL)
As said before I know that this is forbidden in C++. But is there any possibility to use gsl_monte_function_struct with a member function of myClass? If it is not possible that myClass can integrate itself, is it possible to call gsl_monte_function_struct from outside the class with value() as reference? Thanks in advance!
If understand you corretly, you want a pointer to a member function of myClass. You can achieve this by declaring the member function pointer as:
double (myClass::*value)(double,double)
This function can later be called on an instance as:
(instance.*value)(x,y);
Alternatively you can use std::bind to create a function object which can be called as an ordinary function without having to keep track of the instance on which it is called after the call to std::bind:
auto& value = std::bind(myClass::value, instance);
// ....
value(x,y);
Ok so far I found two solutions:
1) (General solution) Using an abstract base class which has a static pointer to the current instance and a static function that calls a function of the derived class. The static function can be used with a function pointer.
Example:
struct gsl_monte{
double (*f)(double y);
};
class myBase {
private:
static myBase* instance;
public:
myBase(){};
static void setInstance(myBase* newOne);
virtual double value(double x) =0;
static double callValue(double x);//{return value(x);}
};
class myClass : public myBase {
public:
myClass(){};
double value(double x) { return x; };
};
myBase* myBase::instance = new myClass();
double myBase::callValue(double x){return instance->value(x);}
void myBase::setInstance(myBase* newOne){instance=newOne;};
double g(double xx) {return xx;};
int main(int argc, char** argv ){
double x[2]; x[0]=1.3; x[1]=1.3;
myClass* instance = new myClass();
myBase::setInstance(instance);
instance->value(3);
std::cout << "Test " << myBase::callValue(5) << std::endl;
gsl_monte T;
T.f=&myBase::callValue;
double (*f)(double y, void*) = &myBase::callValue;
}
2) (Solution specific to my problem) Fortunatly the desired function accepts a parameter pointer, which I can use to pass the current object:
#include <iostream>
#include <functional>
using namespace std::placeholders;
struct gsl_monte{
double (*f)(double y, void*);
};
class myClass {
public:
myClass(){};
double value(double x) { return x; };
};
double valueTT(double x, void* param) { return static_cast<myClass*>(param)->value(x); };
int main(int argc, char** argv ){
double x[2]; x[0]=1.3; x[1]=1.3;
myClass* instance = new myClass();
instance->value(3);
gsl_monte T;
T.f=&valueTT;
double (*f)(double y, void*) = &valueTT;
}

typedef'ing function *signature* (not a pointer to), so that it can be reused?

EDIT: MOTIVATION
Suppose I define a Handler class as
class Handler {
public:
class Message { /*...*/ };
typedef int (*Callback)(Message *msg);
void registerCallback(int msgclass, Callback f);
};
A client can do
int f1(Handler::Message *msg)
{ /* handle message */ }
int f2(Handler::Message *msg)
{ /* handle message */ }
int main(){
Handler h;
h.registerCallback(1, f1);
h.registerCallback(2, f2);
// ....
}
The compiler will indeed check that f1 and f2 are appropriate as parameters to registerCallback, however, it's up to the client to define f1 and f2 correctly. Since I've allready typedefed Callback, I'd like the client to be able to use it instead.
END EDIT
I'd like to do something like this:
typedef int arithmetic(int i, int j);
arithmetic sum
{
return i+j;
}
arithmetic max
{
return (i>j)? i:j;
}
// etc.
However, both
arithmetic sum
arithmetic sum()
don't compile, and also this
arithmetic sum(int i, int j)
which gives compiler error of
func.cpp:4: error: ‘sum’ declared as
function returning a function
The reason I want this is that I want to have a Handler class which would provide a typedef for a callback function it accepts, including the parameter list.
I'll give you a classic C answer, without resorting to the newfangled C++0x toys. Let's start by defining a function prototype:
typedef int TWO_ARG_FUNC(int x, int y);
You can use this prototype when receiving a function pointer, e.g.:
void blah(TWO_ARG_FUNC* funcPtr);
... or when forward-declaring a function:
TWO_ARG_FUNC max;
... but you cannot implement a function by just writing the prototype, e.g.:
TWO_ARG_FUNC max
{
... // bzzt, error!
}
However, not all is lost. You can enforce the function to remain true to a prototype by first forward-declaring it:
TWO_ARG_FUNC max;
int max(int a, int b)
{
...
}
Another option would be to resort to C macros:
#define DEFINE_TWO_ARG_FUNC(funcName) int funcName(int a, int b)
DEFINE_TWO_ARG_FUNC(max)
{
}
and you can even use the macro to declare a function prototype, in case you later want to declare a pointer to such a function:
typedef DEFINE_TWO_ARG_FUNC(TWO_ARG_FUNC);
First, you did not typedef a signature. A signature is everything that identifies a single function. It contains the namespace/class of the function and so on.
What you typedef'ed is the type of a function. Like when you typedef int inttype which typedefs the type of an int, you typedef'ed the type of a function.
You can use the typedef-name to declare functions only.
arithmetic max; // valid
But it cannot be used to define functions. For defining functions, you need to provide a parameter list literally and manually. Reasons include giving names for parameters (and possibly other, more technical reasons. C++0x introduces arithmetic max {}; which will get a specific initialization meaning).
Thinking about your post I will give it a shot about what you want to archive.
You could try using boost or C++0x lambda. I will go with boost.
typedef boost::function<int(int,int)> arithmetic;
arithmetic sum = (boost::lambda::_1 + boost::lambda::_2);
arithmetic max = boost::lambda::if_then_else_return(boost::lambda::_1 > boost::lambda::_2,
boost::lambda::_1, boost::lambda::_2);
int j = sum(3,3); // j ist 6
int k = max(4,2); // k is 4
So maybe this is what you want to archive.
It is also possible with a full blown function.
Here you go.
int FullBodyFunction(int i, int j)
{
return i+j;
}
arithmetic sum2 = boost::bind(&FullBodyFunction, _1, _2);
This will do the same as sum1. You are free to use the whole boost bind stuff. E.g. bind to method of a object or what ever you want.
Since, as you say, you can use C++0x, you might choose to do something like this by typedef'ing a function:
edit, added in your concept of a handler class containing a callback typedef:
#include <functional>
#include <list>
int max(int a, int b)
{
return (a>=b) ? a : b;
}
class Handler
{
public:
//typedef int (*Callback)(int, int);
typedef std::function<int (int, int)> Callback;
void add(Callback func) { functions_.push_back(func); }
private:
std::list<Callback> functions_;
};
int main(int argc, char* argv[])
{
Handler handler;
handler.add([](int a, int b) -> int { return (a>=b) ? a : b; });
handler.add(max);
return 0;
}
This isn't the exact syntax you're looking for, but as others have pointed out, it isn't possible to use typedef for a function signature directly.
I haven't find solution with exact syntax you are looking for, but something like this works:
#include <cassert>
#define arithmetic (int i, int j) -> int
#define declare(Func, Name) auto Name Func
#define as_
auto sum as_ arithmetic
{
return i + j;
};
declare(arithmetic, max)
{
return (i>j) ? i : j;
};
int main()
{
assert(sum(2, 4) == 6);
assert(max(2, 4) == 4);
return 0;
}