Understand building function

good day everyone
I'm trying to build this function that set LCD cursor and print some text

void setAndprint(byte column, byte row, const char msg[]) {
  lcd.setCursor(column, row);
  lcd.print(msg);
}

the target is to reduce program space because I use these two lines alot in my program and it really works nice, but the problem is that I don't want to use this function only with chars (because I declared const char msg[]), I want to print bools or ints. and my function in this case can print only chars, how to make it general, just like lcd.print()

must I write a seperate function for each type ? or there is some magic can I do

thank you

yes you need one function per different type, using overloading
this can also be achieved by template, something like

template<typename T> 
void setAndprint(const byte x, const byte y, T data ) { 
  lcd.setCursor(x, y);
  lcd.print(data);
}

(typed here so untested)

then it would work for anything that print() supports

1 Like

but there is already a print function written for each type, I think there should be a way to not write it again

wow! that's the magic I was talking about
thank you

Otherwise use a macro - it will auto adapt as well

an example please

Something like
#define setAndprint(x, y, data ) { lcd.setCursor((x), (y)); lcd.print((data));}

that's wrong now, defining a function using #define makes the compiler replacing the function literally with its code, the size of code will still huge, so we didn't solve the problem, but we converts it to another shape

Yes that’s why I did not propose this at first. It’s not a function call for sure (but just two so that won’t be as bad as you make it sound…)

with template the compiler will create as many functions as different types you try to pass to it

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