"Generic" Pointer?

To make a short version of my problem, I have a function that needs to take a String or a byte-pointer.

I could achieve that via a function overload, ie:

void myFunction(String *myStr,....){}
void myFunction(byte *myByte,....){}

Is there a way to do that with only one function? Is there a "generic" data pointer that can point to different data formats?

  1. Should i use an void* and send the data size as a parameter?
  2. go with templates?
  3. Use malloc to get the data size in myFunction?
  4. any other way?

For now, i 'll just be handling String and byte, but may have to expand to other datatypes as well.

But if this pointer is "generic", in myFunction() how you can know what kind of variable/object it point?

That's not a good idea, anyway, as you would throw away any type checking for the function. That's one reason why overloading exists as it does in the first place. Don't try to make a function a "Swiss Army Knife"...it will just come back to cut you later on. One function, one task, one signature...

nid69ita:
But if this pointer is "generic", in myFunction() how you can know what kind of variable/object it point?

I don't know... you're the experts here !:slight_smile:

I found some solutions in this thread: Code changing a variable in unexplained way - Programming Questions - Arduino Forum

Overloaded functions are ok, but they take up much more Program memory, and makes code-changing more difficult, since one change must be made in several places. Debugging is more difficult aswell.

hbx2013:
Overloaded functions are ok, but they take up much more Program memory, and makes code-changing more difficult, since one change must be made in several places. Debugging is more difficult aswell.

But every overloaded functions can call a single private function :smiley:

void myFunction(String *myStr,....) {  ...; CommonFunc(); ...;   }
void myFunction(byte *myByte,....) {  ...; CommonFunc(); ...;   }

hbx2013:

nid69ita:
But if this pointer is "generic", in myFunction() how you can know what kind of variable/object it point?

I don't know... you're the experts here !:slight_smile:

You can use void pointers, see here: http://www.cplusplus.com/doc/tutorial/pointers/
section "void pointer". But you need to know what cast do in every situation.

But you need to know what cast do in every situation.

And, you can only use void pointers IF the things pointed to are TRULY interchangeable. For instance, a pointer that points to a char array and a pointer that points to a byte array are truly interchangeable, since both types are the same size.

A pointer to a String and a pointer to an array are NOT interchangeable. You can, as was pointed out, extract the char array from the String, and then call the version that expects an array (probably with a cast).

Or put the String crutch away.