How can I convert a number to a char array conditionally based on template type in Arduino C++

  arduino, arduino-c++, c++, printf, templates

I want to be able to fill a char array string using snprintf or a similar solution. I want to do this with less repetition.

This is to print messages for the class over Serial for verbose debugging.

I do not have access to std and am using Arduino C++ (201103) on a microcontroller where memory is not abundant.

I don’t want to break this up into separate methods for each type as that is more repetitive than the current solution.

Is there any way to add a number to a string based on its type such that whether its a float, double, int, etc, it will print correctly?

My current solution is to just have a lot of "Serial.print"s, which works as it can print all number types with ease, but I dislike how many lines it takes up so knowing a better more compact option would be nice.

The lay of the land:

Template class


template <class Type>
class MyClass
  // Methods - Type
  Type compute(Type input);

  // Variables - string - Printing
  char computePrintBuffer [PRINT_BUFFER_SIZE];
  // Variables - Type - Numbers
  Type variableThatCouldBeAnyTypeOfNumber;

#include "Implementation.tpp"

Implementation file

template <class Type>
Type MyClass<Type>::compute(Type input)
    int result = 0;

    result += snprintf(this->computePrintBuffer, PRINT_BUFFER_SIZE - result, "Number I want to stringify regardless of type is %f", variableThatCouldBeAnyTypeOfNumber);


    return variableThatCouldBeAnyTypeOfNumber;

Source: Windows Questions C++