pointer on method as an argument - c++

To avoid code duplication, I'm tring to pass pointers to functions as arguments of a static method.
I have a class (Geo) with only static methods. One of this methods (+++Geo::traceRay(+++)) should just display(Geo::display(+++)) few things, then return an int.
Another class (Las) needs to use the Geo::traceRay(+++) method, but should display(Las::display(+++)) someting else.
So I try to pass a pointer to function argument to the Geo::traceRay(+++, pointer to function) method. the pointed functon will the right "display()" method.
Up to now, passing the first pointer to display() is not an issue, but I can't find how to do it with the second one.
class Geo
{
public:
static bool display(int pix);
static int traceRay(int start, int end, bool (*func)(int) = &Geo::display); // no issue with this default parameter
};
class Las
{
public:
bool display(int pix);
void run();
};
int Geo::traceRay(int start, int end, bool (*func)(int))
{
for (int i = start; i < end ; ++i )
{
if((*func)(i)) return i;
}
return end;
}
bool Geo::display(int pix)
{
cout << pix*100 << endl;
return false;
}
bool Las::display(int pix)
{
cout << pix << endl;
if (pix == 6) return true;
return false;
}
void Las::run()
{
bool (Las::*myPointerToFunc)(int) = &display; // I can just use display as a non member class, but it should stay a member
Geo::traceRay(0,10, myPointerToFunc); // issue here!
}
int main()
{
Geo::traceRay(0,10); // use the "normal display" = the default one// OK
Las myLas;
myLas.run();
return 0;
}

You can't pass a member function pointer as a function pointer. I presume making Las::display static is not an option. In that case, I would suggest taking a std::function and using std::bind to bind the current instance:
static int traceRay(int start, int end, std::function<bool(int)> func = &Geo::display);
...
Geo::traceRay(0,10, std::bind(&Las::display, this, std::placeholders::_1));
Also, in both cases, you can call func by:
func(i);
No need to dereference it first.

What Chris suggests is great if that's as far as it goes.
Another approach to this, which would be beneficial if you have several shared functions like that, would be to use an interface (with a virtual method Display(+++)) with two implementations, put an instance of the implementation in question in each of Geo and Las (or Las could directly implement the interface). Then traceRay takes a reference to the interface base class and calls the display method on it.

Related

global function and class reference

I want to send integer value in class to global function from main. How should I send it as a parameter,I am sending the parameters wrong
Tetris
{
private:
int num;
}
printBoard(Tetris &t);
int main()
{
Tetris tetris;
printBoard(board,tetris);
}
i want to send num , to printboard.
There are several problems with the shown code.
First, you're missing the class keyword when defining the class.
Second, the return type of the function is also missing.
Third, the function has only one parameter but you're passing two arguments.
i want to send num , to printboard
You can add a getter called getNum which you can use from inside your free function as shown below:
vvvvv------------->added this class keyword
class Tetris
{
private:
int num = 0; //don't forget to initialize
public:
//add a getter
int getNum() const
{
return num; //return a copy
}
};
vvvv----------------------->added return type as void
void printBoard(Tetris &t)
{
std::cout << t.getNum(); //use the getter
}
int main()
{
Tetris tetris;
printBoard(tetris);
}
Demo

Check if class is instantiated in method

I have a class that has a few static functions that can be called even if there is no instance of that class. There is also a method init() that I use to set some variables. This method is not static thus it needs an instance. Now if this was done I want the static methods to behave differently. Sort of like:
static foo(){
if(noInstance()){
doA();
}else(){
doB();
}
}
Is this even possible? Or a bad idea and should just make the user call different methods if there is an instance?
Thanks
EDIT
It sounds weird but this is my use case:
class A{
public:
static inline bool hasInstance = false;
int data;
static int getData(){
if(hasInstance){
return data; // Can't do this from a static function
}else{
return 0;
}
}
};
I know that I cant access the data from a static function beacuse there is no this pointer. I'm coding a library and I want the user to be able to use the static method if he dosen't want an instance but if there is an instance it should make use of the data of its instance.
If had an idea but I don't know wether that's good style:
static int getData(A *ref){
if(ref != nullptr){
return data;
}else{
return 0;
}
}
I'd glad to hear from someone with more experience wether I should do that.
I think you can use a static variable, let it be named count. You initialize count with 0, and every time you create an instance of that class, you increment count. If count is 0, that means you did not created any instance, therefore you can't use some methods.
I'm coding a library and I want the user to be able to use the static method if he dosen't want an instance but if there is an instance it should make use of the data of its instance.
In general, free functions are recommended rather than member functions (gotw). It is actually rare to have good reasons to make a static function a member function. It would need to be a member if it would need access to privates of the class, but that doesnt seem to be the case here and then it still could be a friend function.
Let's look at your approach:
static int getData(A *ref){
if(ref != nullptr){
return data;
}else{
return 0;
}
}
You probably meant to write ref->data;, also I guess you are not merely returning the value of the member. That would be of little use, because If I have an instance I can get my hands on x.data without needing to call getData. And I suppose 0 is just a placeholder for someother value that you have there in the real code.
I am going a bit subjective now...
If I was a user of your library, I would want to know if getData returns data from one of the objects I did create or something else. Having one and the same function that does both would confuse me. I don't like pointers and I am scared of nullpointers, so if you force me to write
getData(nullptr);
this would not make me happy. I would like to have two different functions:
int getData() { return 0; }
int getData(const A& x) { return x.data; }
If I have no instance, I can call the first, if I have one I can call the second.
Not sure what is your final goal, but I would recommend reconsidering your design, because this static/hasInstance behavior smells.
Anyway, here is what you need:
using namespace std;
#include <iostream>
class MyClass
{
private:
static bool hasInstance;
public:
MyClass()
{
hasInstance = true;
}
static void foo()
{
if (hasInstance) {
std::cout << "I have an instance\n";
}
else {
std::cout << "No instance\n";
}
}
};
bool MyClass::hasInstance = false;
int main () {
MyClass::foo();
MyClass a;
a.foo();
MyClass::foo();
return 0;
}
EDIT:
Don't use it in real code. If you just curious, you can do almost everything in C++, so you could pass the object sometimes, it's dirty and ugly, but just for the demo:
using namespace std;
#include <iostream>
class MyClass
{
private:
int someVariable;
public:
MyClass()
{
someVariable = 42;
}
static void foo(MyClass *obj = nullptr)
{
if (obj) {
std::cout << obj->someVariable << std::endl;
}
else {
std::cout << "No instance\n";
}
}
};
int main () {
MyClass::foo();
MyClass a;
a.foo(&a);
MyClass::foo(&a);
return 0;
}

reference to non-static member function must be called error

Im using C++ to create a timer. Ive look up the internet but not find anything that i can understand.Here is my code:
struct Timer{
bool timerRunning;
int time;
void Timer_Service(void* param){
timerRunning = true;
time = 0;
while(timerRunning){
wait(10);
time += 10;
}
}
void startTimer(){
Timer_Service((void*)"PROS");
pros::Task timerservice(Timer_Service,(void*)"PROS");// <- error here "reference to non-static member function must be called"
}
void stopTimer(){
timerRunning = false;
}
int getTime(){
return time;
}
};
How do i solve this error?
BTW pros::Task timerservice(Timer_Service,(void*)"PROS"); is a function that initializes a multitask loop.
Thanks all for your kind help.
The pros::Task constructor takes a function pointer.
Function pointers and pointers-to-member-functions are not the same thing.
You will have to pass a pointer to a non-member function (or a static member), ideally a forwarding delegate. You can create a class that contains a Timer_Service*, and pass it through the void* argument. In fact, in this case, since you only need to pass the object pointer, there's no need for a wrapping class.
struct Timer
{
bool timerRunning;
int time;
static void Timer_Service_Delegate(void* param) {
Timer* ptr = reinterpret_cast<Timer*>(param);
ptr->Timer_Service();
}
void Timer_Service() {
timerRunning = true;
time = 0;
while(timerRunning){
wait(10);
time += 10;
}
}
void startTimer() {
pros::Task timerservice(
Timer_Service_Delegate,
reinterpret_cast<void*>(this)
);
}
void stopTimer() {
timerRunning = false;
}
int getTime() {
return time;
}
};
I suspect you'll also need to keep the pros::Task in scope, but I don't know enough about the library to train you on that. Refer to its documentation.

Static function needing to deal with members of a C++ class

I have to make some kind of bridge between two pieces of software, but am facing an issue I don't know how to deal with. Hopefully someone will have interesting and (preferably) working suggestions.
Here is the background : I have a C++ software suite. I have to replace some function within a given class with another function, which is ok. The problem is that the new function calls another function which has to be static, but has to deal with members of the class. This is this second function which is making me mad.
If the function is not static I get the following error :
error: argument of type ‘void (MyClass::)(…)’ does not match ‘void (*)(…)’
If I set it to static I get either the following error :
error: cannot call member function ‘void
MyClass::MyFunction(const double *)’ without object
or
error: ‘this’ is unavailable for static member functions
depending on if I use or not the "this" keyword ("Function()" or "this->Function()").
And finally, the class object requires some arguments which I cannot pass to the static function (I cannot modify the static function prototype), which prevents me to create a new instance within the static function itself.
How would you deal with such a case with minimal rewriting ?
Edit : Ok, here is a simplified sample on what I have to do, hoping it is clear and correct :
// This function is called by another class on an instance of MyClass
MyClass::BigFunction()
{
…
// Call of a function from an external piece of code,
// which prototype I cannot change
XFunction(fcn, some more args);
…
}
// This function has to be static and I cannot change its prototype,
// for it to be passed to XFunction. XFunction makes iterations on it
// changing parameters (likelihood maximization) which do not appear
// on this sample
void MyClass::fcn(some args, typeN& result)
{
// doesn't work because fcn is static
result = SomeComputation();
// doesn't work, for the same reason
result = this->SomeComputation();
// doesn't work either, because MyClass has many parameters
// which have to be set
MyClass *tmp = new MyClass();
result = tmp->SomeComputation();
}
Pointers to non-static member functions are a bit tricky to deal with. The simplest workaround would just be to add an opaque pointer argument to your function which you can then cast as a pointer to 'this', then do what you need with it.
Here's a very simple example:
void doSomething(int (*callback)(void *usrPtr), void *usrPtr)
{
// Do stuff...
int value = callback(usrPtr);
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
doSomething(myCallback, this);
}
private:
int value_;
static int myCallback(void *usrPtr)
{
MyClass *parent = static_cast<MyClass *>(usrPtr);
return parent->value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
In this example myCallback() can access the private value_ through the opaque pointer.
If you want a more C++-like approach you could look into using Boost.Function and Boost.Bind which allow you to pass non-static member functions as callbacks:
void doSomething(boost::function<int ()> callback)
{
// Do stuff...
int value = callback();
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
doSomething(boost::bind(&MyClass::myCallback, this));
}
private:
int value_;
int myCallback()
{
return value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
If you really can't change the function prototype you could use a global pointer, but that opens up all sorts of issues if you will ever have more than one instance of your class. It's just generally bad practice.
class MyClass;
static MyClass *myClass;
void doSomething(int (*callback)())
{
// Do stuff...
int value = callback();
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
myClass = this;
doSomething(myCallback);
}
private:
int value_;
static int myCallback()
{
return myClass->value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
Following spencercw's suggestion below the initial question I tried the "static member variable that you set to point to this" solution (the global variable would have been tricky and dangerous within the context of the software suite).
Actually I figured out there was already something like this implemented in the code (which I didn't write) :
static void* currentObject;
So I just used it, as
((MyClass*)currentObject)->SomeComputation();
It does work, thanks !!!
non-reentrant and non-thread-safe way is to pass "this" address using global variable.
You can move the result = SomeComputation(); out of your static function and place it in BigFunction right before your call to the static function.

raw function pointer from a bound method

I need to bind a method into a function-callback, except this snippet is not legal as discussed in demote-boostfunction-to-a-plain-function-pointer.
What's the simplest way to get this behavior?
struct C {
void m(int x) {
(void) x;
_asm int 3;
}};
typedef void (*cb_t)(int);
int main() {
C c;
boost::function<void (int x)> cb = boost::bind(&C::m, &c, _1);
cb_t raw_cb = *cb.target<cb_t>(); //null dereference
raw_cb(1);
return 0;
}
You can make your own class to do the same thing as the boost bind function. All the class has to do is accept the function type and a pointer to the object that contains the function. For example, this is a void return and void param delegate:
template<typename owner>
class VoidDelegate : public IDelegate
{
public:
VoidDelegate(void (owner::*aFunc)(void), owner* aOwner)
{
mFunction = aFunc;
mOwner = aOwner;
}
~VoidDelegate(void)
{}
void Invoke(void)
{
if(mFunction != 0)
{
(mOwner->*mFunction)();
}
}
private:
void (owner::*mFunction)(void);
owner* mOwner;
};
Usage:
class C
{
void CallMe(void)
{
std::cout << "called";
}
};
int main(int aArgc, char** aArgv)
{
C c;
VoidDelegate<C> delegate(&C::CallMe, &c);
delegate.Invoke();
}
Now, since VoidDelegate<C> is a type, having a collection of these might not be practical, because what if the list was to contain functions of class B too? It couldn't.
This is where polymorphism comes into play. You can create an interface IDelegate, which has a function Invoke:
class IDelegate
{
virtual ~IDelegate(void) { }
virtual void Invoke(void) = 0;
}
If VoidDelegate<T> implements IDelegate you could have a collection of IDelegates and therefore have callbacks to methods in different class types.
Either you can shove that bound parameter into a global variable and create a static function that can pick up the value and call the function on it, or you're going to have to generate per-instance functions on the fly - this will involve some kind of on the fly code-gen to generate a stub function on the heap that has a static local variable set to the value you want, and then calls the function on it.
The first way is simple and easy to understand, but not at all thread-safe or reentrant. The second version is messy and difficult, but thread-safe and reentrant if done right.
Edit: I just found out that ATL uses the code generation technique to do exactly this - they generate thunks on the fly that set up the this pointer and other data and then jump to the call back function. Here's a CodeProject article that explains how that works and might give you an idea of how to do it yourself. Particularly look at the last sample (Program 77).
Note that since the article was written DEP has come into existance and you'll need to use VirtualAlloc with PAGE_EXECUTE_READWRITE to get a chunk of memory where you can allocate your thunks and execute them.
#include <iostream>
typedef void(*callback_t)(int);
template< typename Class, void (Class::*Method_Pointer)(void) >
void wrapper( int class_pointer )
{
Class * const self = (Class*)(void*)class_pointer;
(self->*Method_Pointer)();
}
class A
{
public:
int m_i;
void callback( )
{ std::cout << "callback: " << m_i << std::endl; }
};
int main()
{
A a = { 10 };
callback_t cb = &wrapper<A,&A::callback>;
cb( (int)(void*)&a);
}
i have it working right now by turning C into a singleton, factoring C::m into C::m_Impl, and declaring static C::m(int) which forwards to the singleton instance. talk about a hack.