Reputation: 737
How can I assign member function which is overloaded to other member function (or function pointer) in C++?
My objective is to wrap member function. I have following code and it doesn't work because it has 2 "Do"s. What I want to do is wrapping Do1
or Do2
to Do
with any double *
or double **
. Hence, I can run only Do
and don't need to care about Do1
or Do2
. (Maybe, I should specify condition that need to be chosen between Do1
and Do2
.)
class Sample {
int (*Do)(double *arr);
int (*Do)(double **arr);
int Do1(double *arr);
int Do1(double **arr);
int Do2(double *arr);
int Do2(double **arr);
};
Or do you have any suggestions for this objective?
Addition : For Thomas, function objects(functors) is a good idea, but it only resolves overloading. I want to choose function (ex, Do1
or Do2
). I have several prescribed functions and I can make choose one of them to Do
. However, I also want to assign custom function to Do
.
For example when I run Do
, I could run Do1
, Do2
, or my own new customized function. (I should set what function will be executed when I make a instance)
and.. I can't use C++11 in my situation. (I want to, but my server has a older GCC versions)
Upvotes: 2
Views: 116
Reputation: 12108
Your code is ill-formed and will NOT compile. You can overload function, but not objects! That is, you cannot have two pointers named 'Do' with different types. I can't recall perfectly, but MSVC would tell you something like this:
'Sample::Do' : redefinition; different basic types
If you want to do something like that, you can use flag:
class Sample
{
int Do(double *arr);
int Do(double **arr);
int Do1(double *arr);
int Do1(double **arr);
int Do2(double *arr);
int Do2(double **arr);
void SetDoVersion(int version);
int _do_version;
};
And 'Do' would look like this:
int Sample::Do(double *arr)
{
//For more than 2-3 versions you could also use switch().
if(this->_do_version == 1)
return this->Do1(arr);
else
return this->Do2(arr);
}
int Sample::Do(double **arr)
{
//same as above
}
SetDoVersion() sets currently 'installed' version:
void Sample::SetDoVersion(int version)
{
this->_do_version = version;
}
This is probably the simplest solution for this task.
Upvotes: 1