How to assign member function to member function pointer with overloading? - c++

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)

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.

Related

How can I pass only a few default parameters?

I created a function like:
void triangle(int n, int start=1, int spcs=0, char dec_y='n', char lf='#',char decf='o') {
//some code
}
I wanted to know is there any way that I could call this function like this:
triangle(9, dec_y='y', lf='&');
without doing this:
void triangle2(int nn, char d_ec_y, char llf) {
triangle(nn, 1, 0, d_ec_y, llf, 'o');
}
// then in main simply
triangle2(9, 'y', '&');
You can't change the order of the parameters. So you can't do what you want directly. You have three options:
One that you don't want to.
You can pass the parameters as structure. The struct can have default values. And you can only alter the ones which you want before calling the function.
For example:
struct params
{
params(int n_)
:n(n_)
{
}
int start=1;
int spcs=0;
char dec_y='n';
char lf='#';
char decf='o';
};
...
params p(0);
p.dec_y='y';
p.lf='&';
triangle(p);
You can use boost::parameter which provides exactly what you want. Check this question for a sample usage.
No, c++ requires that any parameters for which the default parameter will be used come after all specified parameters.
In some circumstances this can be worked around by having multiple overloads. But due to argument ambiguity that is not always possible. The idea is to leave out some of the middle arguments, as in:
void foo(int, char const *, int =0);
void foo(int, int=0);
This pair always requires the first int but allows that to be followed by either a string or another int, and if the string version is used still allows the final int argument.
Using some advanced meta-programming it is actually possible to make all the arguments optional and to supply them in any order without declaring any overloads. For example this is implemented in boost.process API:
namespace bp = ::boost::process;
bp::environment env{::boost::this_process::environment()};
bp::child ch0("cmd", env); // ok
bp::child ch1("cmd", env, bp::windows::hide); // fine too
bp::child ch2("cmd", bp::windows::hide, env); // still fine
bp::child ch3("cmd", bp::windows::hide); // no problem
The idea behind this is that each supported argument is wrapped into a trait class that supplies manipulation method(s) and all those calls invoke the same template function which invokes manipulation method for each supplied argument.

Wrapper function only sees itself?

Sorry for the vague title. I don't know how to phrase this issue.
I am practicing the use of pointers in C++ by rewriting a mergesort program by passing reference, but have run into an issue. To create a scratch array in a non-recursive method, I made the wrapper function...
void mergesort(int *low, int *high){
int *barr = new int[high-low+1];
mergesort(*low, *high, *barr);
}
...which in the end calls the function...
void mergesort(int *low, int *high, int *barr){
int *mid;
if(high - low < 2)
return;
int interval = high - low;
*mid = interval/2;
mergesort(low, mid, barr);
mergesort(mid, high, barr);
merge(low, high, barr);
}
...but I am getting the error 'mergesort': function does not take 3 arguments. Well, no duh, Visual Studio. Why does it not see the latter function instead of calling itself?
I tried fixing the issue originally by throwing away clever coding conventions and just renaming the wrapper function mergesortwrap(int *low, int *high) and changing the call in the main, but then I get the error 'mergesort': identifier not found. I am a Java kiddie. I don't understand this at all. Many thanks to anyone who can help.
Unlike in some other languages, free function declarations are not "hoisted" in C++. They are only available where they have been previously declared (or when you're inside a member function definition and are trying to name another member function).
That is why headers, which are typically included at the top of source files, conventionally have declarations:
void mergesort(int *low, int *high, int *barr);
void mergesort(int *low, int *high);
Then you can define them wherever you want but everywhere will be aware that these functions exist… including in the functions themselves.
A quick fix in your particular case is to swap the definitions around, since the overload taking three arguments doesn't need to know about the overload taking two arguments.
You need to write a forward declaration of the 3-legged overload before using it:
void mergesort(int *low, int *high, int *barr);
void mergesort(int *low, int *high){
int *barr = new int[high-low+1];
mergesort(*low, *high, *barr); // OK now
}
Alternatively, you can also define the 3-legged overload before the 2-legged one, but if the former would also call the latter, then you'd still have to forward declare it.
The only exception is when both functions are members of a class, because the whole class definition is being parsed before the member definitions.

C++, how to call functions when reading their ID number from a Mysql table?

I have a Mysql table that I am using as a list of different calculations that needs to be done.
Each line in the table has a column of type INT that has the number of the function that needs to be called.
e.g. line 6, data, (function) 1.
I read all the lines one by one and I need to call the relevant functions for each line.
What is the best way to construct it in C++?
should I have another function that returns the pointer of the functions that needs to be called ?
Are there other recommended solutions?
Thanks
It depends on the type of the function (input/outputs) but assuming they are all the same, you can make an array of function pointers. For example:
std::vector<void(*)(int)> MyArray;
Will declare an array of function pointers returning void and taking one int as parameter. Then you can put the functions you want in it and when you want to call them you can use MyArray[i]
If the actual type for the function pointer is long and hard to type, you can use decltype(MyFunction) instead. This requires C++11 though.
Using function pointers may work may work but I would rather make use of something like Strategy pattern.
class DataProcessor {
public:
virtual void process(Data& data) = 0;
// some other things like dtors etc
}
For each type of "function" you can create its corresponding DataProcessor.
To ease lookup, you may make use of a factory, or simply a std::map<int, DataProcessor> (instead of using int as key, will you consider using an enum?), or even a vector/array of DataProcessor.
As a suggestion, this is another way:
//Create only a function and make a switch statement in it:
void myfunction (std::pair<int,int> aRow) { // function:
int result;
int data = aRow.second;
int function_id = aRow.second;
switch(function_id){
case 1:{
//Funcion with any signature
break;
}
case 2:{
//Funcion with another signature
break;
}
//and so on...
}
//do something with the result...
}
int main () {
//Fetch your mysql data here:
std::vector<std::pair<int, int> > myMySQLdata;
for_each (myMySQLdata.begin(), myMySQLdata.end(), myfunction);
}

Using var_arg to pass parameters for function calls

I am writing an adapter to combine two APIs (one in C and another in C++).
If a function is called on the one API I need to pass the callers ID and the function's arguments to an adapter and call the according function with this information passed.
Now aparently they can not be mapped directly as one interface requires C++ compilation and the name mangling would screw the other so that is why I am using a set of adapters in the first place.
As the number of arguments varies, I looked up variadic functions and found the idea pretty useful, however I am operating on POD only and have to deal with structs, enums and a lot of different arguments per call, which might need to be put back into a struct before feeding it to the target function.
Every example I stumbled upon was far simpler and involved mostly arithmetic operations like summing stuff up , finding largest numbers or printing. Mostly done with for loops on the var_list.
Maybe I got stuck on the idea and it won't work at all, but I am just curious...
Say I wanted to assign the arguments from the list to my target functions parameters (the order of the arguments passed is the correct one), what would be a good way?
BOOL Some_Function(
/* in */ CallerId *pObjectId,
/* in */ someDataType argument1 )
{
BOOL ret = Adapter_Call(pFunction, pObjectId, argument1);
return ret;
}
and so once I made it to the right adapter I want to do
BOOL Adapter_Call(*pFunction, *pObjectId, argument1, ...)
{
va_list args;
va_start(args, argument1);
/*go over list and do `var_list[i] = pFunctionArgList[i]` which is
of whatever type so I can use it as input for my function */
va_end(args);
pObjectId.pFunction(arg1,...,argn);
}
Can I access the input parameters of a function to perform assignments like this?
Has anyone done something like this before? Is there a conceptual mistake in my thinking?
All I found on the net was this, http://www.drdobbs.com/cpp/extracting-function-parameter-and-return/240000586but due to the use of templates I am not sure if it wouldn't create another problem and so in the end implementing an adapter for each and every single functioncall may be simpler to do.
A SO search only returned this: Dynamic function calls at runtime (va_list)
First, you should heed Kerrek's advice about extern "C". This is C++'s mechanism for giving an identifier C linkage, meaning that the name won't be mangled by the C++ compiler.
Sometimes, and adapter still needs to be written for a C++ interface, because it manipulates objects that do not map to a C POD. So, the adapter gives the C interface a POD or opaque pointer type to manipulate, but the implementation of that interface converts that into an C++ object or reference and then calls the C++ interface. For example, suppose you wanted to provide a C interface for C++ std::map<int, void *>, you would have a common header file in C and C++ that would contain:
#ifdef __cplusplus
extern "C" {
#endif
struct c_map_int_ptr;
// ...
// return -1 on failure, otherwise 0, and *data is populated with result
int c_map_int_ptr_find (struct c_map_int_ptr *, int key, void **data);
#ifdef __cplusplus
}
#endif
Then, the C++ code could implement the function like:
typedef std::map<int, void *> map_int_ptr;
int c_map_int_ptr_find (struct c_map_int_ptr *cmap, int key, void **data) {
map_int_ptr &map = *static_cast<map_int_ptr *>(cmap);
map_int_ptr::iterator i = map.find(key);
if (i != map.end()) {
*data = i->second;
return 0;
}
return -1;
}
Thus, there is no need to pass the arguments passed via the C interface through a variable argument adapter. And so, there is no need for the C++ code to tease out the arguments from a variable argument list. The C code calls directly into the C++ code, which knows what to do with the arguments.
I suppose if you are trying to implement some kind of automated C adapter code generator by parsing C++ code, you could think that using variable arguments would provide a regular mechanism to communicate arguments between the generated C code interface and the generated C++ adapter code that would call the original C++ interface. For such a scenario, the code for the above example would look something like this:
// C interface
typedef struct c_map_int_ptr c_map_int_ptr;
typedef struct c_map_int_ptr_iterator c_map_int_ptr_iterator;
//...
c_map_int_ptr_iterator c_map_int_ptr_find (c_map_int_ptr *map, int key) {
c_map_int_ptr_iterator result;
cpp_map_int_ptr_adapter(__func__, map, key, &result);
return result;
}
// C++ code:
struct cpp_adapter {
virtual ~cpp_adapter () {}
virtual void execute (va_list) {}
};
void cpp_map_int_ptr_adapter(const char *func, ...) {
va_list ap;
va_start(ap, func);
cpp_map_int_ptr_adapter_method_lookup(func).execute(ap);
va_end(ap);
}
//...
struct cpp_map_int_ptr_find_adapter : cpp_adapter {
void execute (va_list ap) {
map_int_ptr *map = va_arg(ap, map_int_ptr *);
int key = va_arg(ap, int);
c_map_int_ptr_iterator *c_iter = va_arg(ap, c_map_int_ptr_iterator *);
map_int_ptr::iterator i = map->find(key);
//...transfer result to c_iter
}
};
Where cpp_map_int_ptr_adapter_method_lookup() returns an appropriate cpp_adapter instance based on a table lookup.

c++ std::map of heterogeneous function pointers

Is it possible to store pointers to various heterogenous functions like:
In the header:
int functionA (int param1);
void functionB (void);
Basically this would the part I don't know how to write:
typedef ??boost::function<void(void)>?? functionPointer;
And afterwards:
map<char*,functionPointer> _myMap;
In the .cpp
void CreateFunctionMap()
{
_myMap["functionA"] = &functionA;
_myMap["functionB"] = &functionB;
...
}
And then reuse it like:
void execute(int argc, char* argv[])
{
if(argc>1){
int param = atoi(argv[1]);
int answer;
functionPointer mfp;
mfp = map[argv[0]];
answer = *mfp(param);
}
else{
*map[argv[0]];
}
}
etc.
Thanks
--EDIT--
Just to give more info:
The reason for this question is that I am implementing a drop-down "quake-style" console for an already existing application. This way I can provide runtime command line user input to access various already coded functions of various types i.e.:
/exec <functionName> <param1> <param2> ...
If you want to have "pointer to something, but I'm not going to define what, and it could be a variety of things anyway" you can use void *.
But you really shouldn't.
void * is purely a pointer. In order to do anything with it, you have to cast it to a more meaningful pointer, but at that point, you've lost all type safety. What's to stop someone from using the wrong function signature? Or using a pointer to a struct?
EDIT
To give you a more useful answer, there's no need to put this all into a single map. It's ok to use multiple maps. I.e.
typedef boost::function<void(void)> voidFunctionPointer;
typedef boost::function<int(int)> intFunctionPointer;
map<std::string, voidFunctionPointer> _myVoidMap;
map<std::string, intFunctionPointer > _myIntMap;
void CreateFunctionMap()
{
_myVoidMap["functionA"] = &functionA;
_myIntMap["functionB"] = &functionB;
...
}
void execute(int argc, char* argv[])
{
if(argc>1){
int param = atoi(argv[1]);
int answer;
// todo: check that argv[0] is actually in the map
intFunctionPointer mfp = _myIntMap[argv[0]];
answer = mfp(param);
}
else{
// todo: check that argv[0] is actually in the map
voidFunctionPointer mfp = _myVoidMap[argv[0]];
mfp();
}
}
You can use
boost::variant<
boost::function<void(void)>,
boost::function<void(int)> >
Why not just add functions of type int (*func)(int argc, char* argv[])? You could easily remove first arg from execute's params and call the relevant one.
Can you not use the command pattern to encapsulate the function calls. So you can store the functions in functors and call them after wards. For functor implementation you can have a look at Modern C++ Design by Andrei Alexandrescu.
Each of your functions has a different type, so you need some kind of type erasure. You could use the most generic of them: Boost.Any. You can have a map of boost::any, but you need to know the type of the function in order to get it back and call it.
Alternatively, if you know your arguments ahead of time you can bind them with the function call and have all functions in the map be nullary functions: function< void() >. Even if you don't, you may be able to get away with it by binding the argument to references, and then at call time fill the referred variables with the appropiate arguments.