I want to have a function within a class to start a task with another function in the class
class taskTest{
public:
int test(void*){
return 0;
}
void startTask(){
vex::task t(test);
}
};
but I get
reference to non-static member function must be called
I’ve tried for about an hour to get this to work and I can’t figure anything out
Any help would be appreciated
TLDR; you can’t do that.
A task is really a callback from the vexos scheduler, it needs to be a static member function.
you would need to declare like this.
static int test(void){
return 0;
}
see this for lots more details.
http://p-nand-q.com/programming/cplusplus/using_member_functions_with_c_function_pointers.html
If you need to access non-static members in your task, you could possibly do something a bit janky like this if you really want:
#include "robot-config.h"
class MyClass {
static MyClass* taskInstance;
static vex::mutex& getTaskInstanceGuard() {
static vex::mutex guard;
return guard;
}
static int _task() {
MyClass* self = taskInstance;
if (self == nullptr) {
return 0;
}
self = nullptr;
getTaskInstanceGuard().unlock();
// Then you can use member functions (even private ones)
self->doSomething();
return 0;
}
void doSomething() {
Brain.Screen.print("Hello world");
}
public:
void startTask() {
getTaskInstanceGuard().lock();
taskInstance = this;
vex::task task(_task);
}
};
MyClass* MyClass::taskInstance = nullptr;
int main() {
MyClass obj;
obj.startTask();
}
It compiles, but I can’t guarantee it would work.
It is to be noted that if an instance of your class were to be destructed and it’s task still running, you’ll probably segfault if you try and do anything with
self
This also might not work for multiple instances of the same class running classes simultaneously, that depends on how the scheduler works. (The reason I think it might not is because of the vex::task.stop overload that accepts in a function pointer, however, vex::thread doesn’t have an equivalent, so it might work with vex::thread?).
If it does work, you could probably make it quite elegant with a template class.