FuncPtrs/Templates (I'm way over my head!)

I'm way over my head here.... But trying to piece this together mostly to see if it's even possible, and to help myself learn about function pointers and templates. I just about understand the examples I've got working but I'm over-reaching for sure.

So...

This example of a function pointer works:

////// Function Pointer Test
void (*btnFuncPtr)(void);
void execute(){ btnFuncPtr(); }
void Test1() { Serial.println("Test 1 Worked"); }
void setup() { Serial.begin(9600); }

void loop() {
  btnFuncPtr = &Test1;
  execute();
  while(1);
}

But I can only hook in a void function that takes no parameters.

This example of a template that takes any number of arguments (of any types) works:

/////// Multiple Argument Test
template <typename T>
void func(T t) { Serial.println(t); }

template<typename T, typename... Args>
void func(T t, Args... args) {
    Serial.println(t);
    func(args...) ;
}

void setup() { Serial.begin(9600); }

void loop() {
  func(1, "This is", 6.9f, "A", "Test");
while(1);
}

For no reason other than my own amusement and learning I'm trying to combine the two.
So I can essentially have a function pointer to any function, no matter what or how many arguments are required.

Can it be done?

What is the purpose of a template function if no specific type is required for it?

Guess you have already found this.

That is the beauty and the horror of C. Yes. You can do almost anything.

The goal is to have the function pointer point to any function, no matter what or how many arguments are required. Is the template not even needed for this?

I did see that, yes! Although it's just as much over my head. Maybe the answer is in there but I do not see it yet. (Plenty of studying left to do)

Then what?

Haven't decided yet. Just exploring to see what's possible. The thought process started because I gave my button class function pointers to call when pressed. Which is fine for void functions with no parameters but I thought 'what if I wanted to hook in other functions that looked a little or very different'. Sure you could probably write a million overloads. But maybe templates are the answer. Who knows!

you can define function ptrs to functions with a specified set of arguments. it's common to specify a void* argument which can then be cast to the type needed by the function

see variadic functions for functions with a variable # of arguments.

Those are nicknamed, "callback" functions. As they don't expect to return any values, they also don't accept any parameters. That makes them a lot safer than calling void function pointers from a main program, and/or passing parameters with them. They're normally just event handlers.

This was more of a 'can it be done' than a 'should it be done' really.

But if it can be done, I can't suss it :joy:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.