# How to declare callback with Printable return type?

**URL:** <https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702>\
**Category:** Programming\
**Created:** [April 18, 2023, 1:41pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702 "2023-04-18T13:41:07Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![el\_pablo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/el_pablo/32/1013044_2.png) [@el\_pablo](https://forum.arduino.cc/u/el_pablo)\
**Post date:** [April 18, 2023, 1:41pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/1 "2023-04-18T13:41:07Z")

</div>

Hi,

I want to set a callback member function that could return any printable type, not only `String` or `char[]`. How can I do that?

```cpp
#include <List.hpp>

/**
 * @brief Class that extends the LiquidCrystal_I2C library to add some features such as message queueing and scrolling.
 * 
 */
class LCD_I2C_Extended : public LiquidCrystal_I2C {
    public:
      List<String (*)()> getCallbacks() {return _callbacks;};
      
      // Would like to have something more generic such as Print
      void addCallback(String (*callback)()) {
        _callbacks.add(callback);
      };
      

    private:
      
      // HOW TO GET callbacks with return type that are printables such as String, char*, int, ...
      List<String (*)()> _callbacks;
        
};

#endif

```

I've tried with `Printables`, but without success.

Thanks for any help!

---

<div class="post-metadata">

**Author:** ![Juraj](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/juraj/32/238785_2.png) [@Juraj](https://forum.arduino.cc/u/Juraj)\
**Post date:** [April 18, 2023, 1:44pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/3 "2023-04-18T13:44:03Z")

</div>

could you show us some example how do you want to use it?

---

<div class="post-metadata">

**Author:** ![el\_pablo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/el_pablo/32/1013044_2.png) [@el\_pablo](https://forum.arduino.cc/u/el_pablo)\
**Post date:** [April 18, 2023, 1:56pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/4 "2023-04-18T13:56:45Z")

</div>

Something around this.

```cpp
#include "LCD_I2C_Extended.h"

LCD_I2C_Extended lcd (0x27, 16, 2);

String testCallbacks() {
  return "Potatoes!";
}

void setup() {
  lcd.init();
  lcd.addCallback(testCallbacks);
}

void loop() {
  // put your main code here, to run repeatedly:
  
  lcd.upate();
}

```

The goal is to create an LCD that is going to scroll through messages at a given interval. These messages are returned by functions.

---

<div class="post-metadata">

**Author:** ![Juraj](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/juraj/32/238785_2.png) [@Juraj](https://forum.arduino.cc/u/Juraj)\
**Post date:** [April 18, 2023, 2:04pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/5 "2023-04-18T14:04:56Z")

</div>

remove the \* from `String (*)()`

---

<div class="post-metadata">

**Author:** ![el\_pablo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/el_pablo/32/1013044_2.png) [@el\_pablo](https://forum.arduino.cc/u/el_pablo)\
**Post date:** [April 18, 2023, 2:57pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/6 "2023-04-18T14:57:51Z")

</div>

I need the `*` because it's a function pointer. The list will contains function pointers to call.

---

<div class="post-metadata">

**Author:** ![gfvalvo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gfvalvo/32/1013044_2.png) [@gfvalvo](https://forum.arduino.cc/u/gfvalvo)\
**Post date:** [April 18, 2023, 3:23pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/7 "2023-04-18T15:23:50Z")

</div>

Post a complete code.

---

<div class="post-metadata">

**Author:** ![el\_pablo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/el_pablo/32/1013044_2.png) [@el\_pablo](https://forum.arduino.cc/u/el_pablo)\
**Post date:** [April 18, 2023, 3:33pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/8 "2023-04-18T15:33:47Z")

</div>

Like I said, I would like to have some callbacks more generic than "String". I though there was a generic printable type.

```cpp
#include "LCD_I2C_Extended.h"

LCD_I2C_Extended lcd (0x27, 16, 2);

String testCallbacks() {
  return "Potatoes!";
}

String testCallbacks2() {
  return "Apple!";
}

void setup() {
  Serial.begin(9600);
  //lcd.init();
  lcd.addCallback(testCallbacks);
  lcd.addCallback(testCallbacks2);
}

void loop() {  
  lcd.update();
}

```

Class

```cpp

#ifndef LCD_I2C_EXTENDED_H
#define LCD_I2C_EXTENDED_H

#include "Printable.h"
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <List.hpp>

/**
 * @brief Class that extends the LiquidCrystal_I2C library to add some features such as message queueing and scrolling.
 * 
 */
class LCD_I2C_Extended : public LiquidCrystal_I2C {
    public:
      LCD_I2C_Extended (uint8_t lcd_Addr,uint8_t lcd_cols,uint8_t lcd_rows) : LiquidCrystal_I2C(lcd_Addr, lcd_cols,lcd_rows) {};
      void setMessageInterval(int interval) {_interval = interval ;};
      void update();
      List<String (*)()> getCallbacks() {return _callbacks;};
      
      void addCallback(String (* callback)()) {
        _callbacks.add(callback);
      };
      

    private:
      unsigned int _interval = 3000;
      unsigned long currentTime = 0;
      int _currentIdx = 0;
      
      // List of callbacks that returns String
      List<String (*)()> _callbacks;
        
};

void LCD_I2C_Extended::update(){
  static unsigned long lastTime = 0;
  
  currentTime = millis();
  
  if (currentTime - lastTime < _interval) return;
  
  if (_callbacks.isEmpty()) return;
  
  lastTime = currentTime;
  
  Serial.print(_callbacks.getValue(_currentIdx++)());
  
  _currentIdx = _currentIdx > _callbacks.getSize() - 1 ? 0 : _currentIdx;
  
  
}

#endif

```

---

<div class="post-metadata">

**Author:** ![westfw](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/westfw/32/213443_2.png) [@westfw](https://forum.arduino.cc/u/westfw)\
**Post date:** [April 18, 2023, 4:39pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/9 "2023-04-18T16:39:40Z")

</div>

> [@el\_pablo](#):
>
> I want to set a callback member function that could return any printable type

I don't believe that this is possible. C++ polymorphism is a compile-time feature, and values do not include type information at run-time.

(I mean, you can CREATE objects that potentially include a "print" method, and have a higher-level printer that invokes those methods, but that's not how the Arduino print functions work.)

---

<div class="post-metadata">

**Author:** ![gfvalvo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gfvalvo/32/1013044_2.png) [@gfvalvo](https://forum.arduino.cc/u/gfvalvo)\
**Post date:** [April 18, 2023, 5:17pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/10 "2023-04-18T17:17:04Z")

</div>

> [@el\_pablo](#):
>
> I though there was a generic printable type.

Inheriting from Printable allows a class to print itself via the Print class. So if you make your callbacks classes that inherit from Printable :

```arduino
#include "Printable.h"

class Callback : public Printable {
  public:
    virtual size_t printTo(Print &p) const = 0;
};

class StringCallback : public Callback {
  public:
    virtual size_t printTo(Print &p) const {
      return p.println("Potatoes");
    }
};

class NumberCallback : public Callback {
  public:
    virtual size_t printTo(Print &p) const {
      return p.println(number, 5);
    }

  private:
    float number = 3.14159;
};

void setup() {
  Serial.begin(115200);
  delay(2000);

  StringCallback cb1;
  NumberCallback cb2;

  Callback *callbacks[] = {&cb1, &cb2};

  Serial.print(*callbacks[0]);
  Serial.print(*callbacks[1]);
}

void loop() {
}
```

**Output:**

```arduino
Potatoes
3.14159

```

---

<div class="post-metadata">

**Author:** ![westfw](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/westfw/32/213443_2.png) [@westfw](https://forum.arduino.cc/u/westfw)\
**Post date:** [April 18, 2023, 6:49pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/11 "2023-04-18T18:49:52Z")

</div>

> [@gfvalvo](#):
>
> Inheriting from Printable allows a class to print itself via the Print class.

I hadn't noticed `Printable.h` before! Neat.

However:

> [want to print] any printable type, not only `String` or `char[]`.

Printable.h says:

> The Printable class provides a way for **new** classes to allow themselves to be printed.

The "new classes" is significant. In order for something to be "Printable", it has to be a class, and it has to have inherited from the Printable class, and defined a printTo() method. Basic types like int or char[] are not printable (and a bit strangely, Arduino's "String" type doesn't seem to be Printable, either.)

---

<div class="post-metadata">

**Author:** ![gfvalvo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gfvalvo/32/1013044_2.png) [@gfvalvo](https://forum.arduino.cc/u/gfvalvo)\
**Post date:** [April 18, 2023, 6:54pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/12 "2023-04-18T18:54:33Z")

</div>

> [@westfw](#):
>
> Basic types like int or char[] are not printable (and a bit strangely, Arduino's "String" type doesn't seem to be Printable, either.)

The Print class already knows how to print those types. The purpose of the Printable class is to allow the Print class to print custom types (classes & structs) by having the type itself implement printTo(). The class then "prints itself" anyway it wants using the Print class reference that's passed in.

---

<div class="post-metadata">

**Author:** ![el\_pablo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/el_pablo/32/1013044_2.png) [@el\_pablo](https://forum.arduino.cc/u/el_pablo)\
**Post date:** [April 18, 2023, 7:11pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/13 "2023-04-18T19:11:17Z")

</div>

I guess the `Print` class with `printTo() `is similar to `public override string ToString(){/**/}` in C#.

---

<div class="post-metadata">

**Author:** ![Juraj](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/juraj/32/238785_2.png) [@Juraj](https://forum.arduino.cc/u/Juraj)\
**Post date:** [April 19, 2023, 4:52am UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/14 "2023-04-19T04:52:54Z")

</div>

> [@westfw](#):
>
> I hadn't noticed `Printable.h` before! Neat.

class IPAddress is Printable

---

<div class="post-metadata">

**Author:** ![hamarn](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/hamarn/32/964557_2.png) [@hamarn](https://forum.arduino.cc/u/hamarn)\
**Post date:** [April 19, 2023, 9:52am UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/15 "2023-04-19T09:52:49Z")

</div>

I added the "unsigned long" type to your code for reference.  
[Click here: Wokwi Simulattion](https://wokwi.com/projects/362425921075727361)

```cpp
#include "LCD_I2C_Extended.h"

LCD_I2C_Extended lcd (0x27, 16, 2);

String testCallbacks() {
  return "Potatoes!";
}

String testCallbacks2() {
  return "Apple!";
}

unsigned long testCallbacks3() {
  return -1;
}

void setup() {
  Serial.begin(9600);
  //lcd.init();
  lcd.addCallback(testCallbacks);
  lcd.addCallback(testCallbacks2);
  lcd.addCallback(testCallbacks3);
}

void loop() {  
  lcd.update();
}

```

Class:

```cpp
#ifndef LCD_I2C_EXTENDED_H
#define LCD_I2C_EXTENDED_H

#include "Printable.h"
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <List.hpp>

/**
   @brief Class that extends the LiquidCrystal_I2C library to add some features such as message queueing and scrolling.

*/
class LCD_I2C_Extended : public LiquidCrystal_I2C {
  public:
    LCD_I2C_Extended (uint8_t lcd_Addr, uint8_t lcd_cols, uint8_t lcd_rows) : LiquidCrystal_I2C(lcd_Addr, lcd_cols, lcd_rows) {};
    void setMessageInterval(int interval) {
      _interval = interval ;
    };
    void update();
    List<String (*)()> getCallbacks() {
      return _callbacks;
    };

    void addCallback(String (* callback)()) {
      _callbacks.add(callback);
    }

    void addCallback(unsigned long (* callback)()) {
      _ulCallbacks.add(callback);
    };

  private:
    unsigned int _interval = 3000;
    unsigned long currentTime = 0;
    int _currentIdx = 0;
    int _currentULIdx = 0;
    int _typeIdx = 0;

    // List of callbacks that returns String
    List<String (*)()> _callbacks;
    List<unsigned long (*)()> _ulCallbacks;

};

void LCD_I2C_Extended::update() {
  static unsigned long lastTime = 0;

  currentTime = millis();

  if (currentTime - lastTime < _interval) return;
  lastTime = currentTime;

  switch (_typeIdx) {
    case 0:
      if (_callbacks.isEmpty()) return;
      Serial.println(_callbacks.getValue(_currentIdx++)());
      if (_currentIdx > _callbacks.getSize() - 1) {
        _currentIdx = 0;
        _typeIdx++;
      }

      break;
    case 1:
      if (_ulCallbacks.isEmpty()) return;
      Serial.println(_ulCallbacks.getValue(_currentULIdx++)());
      if (_currentULIdx > _ulCallbacks.getSize() - 1) {
        _currentULIdx = 0;
        _typeIdx = (_typeIdx + 1) % 2; // Max Type = 2;
      }
      break;
  }
}

#endif

```

---

<div class="post-metadata">

**Author:** ![gfvalvo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gfvalvo/32/1013044_2.png) [@gfvalvo](https://forum.arduino.cc/u/gfvalvo)\
**Post date:** [April 19, 2023, 12:11pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/16 "2023-04-19T12:11:38Z")

</div>

> [@el\_pablo](#):
>
> I though there was a generic printable type.

You can also return a variant type. C++17 has std::variant, but I don't think most Arduino packages have that version. But, you can roll your own. I wrote this code for a somewhat related forum question:

```arduino
class BaseClass {
  public:
    class VariantType {
      public:
        enum DataType {NO_TYPE, U32_TYPE, I32_TYPE, FLOAT_TYPE, STRING_TYPE};

        VariantType(): dataType(NO_TYPE) {
        }

        VariantType(uint32_t u) : dataType(U32_TYPE), u32(u) {
        }

        VariantType(int32_t i) : dataType(I32_TYPE), i32(i) {
        }

        VariantType(float f) : dataType(FLOAT_TYPE), fl(f) {
        }

        VariantType(const String s) : dataType(STRING_TYPE), str(new String(s)) {
        }

        VariantType(const VariantType &rhs) {
          copyMove(const_cast<VariantType &>(rhs));
        }

        VariantType(VariantType &&rhs) {
          copyMove(rhs, true);
        }

        VariantType &operator=(const VariantType &rhs) {
          if (dataType == STRING_TYPE) {
            delete str;
          }
          copyMove(const_cast<VariantType &>(rhs));
          return *this;
        }

        VariantType &operator=(VariantType &&rhs) {
          if (dataType == STRING_TYPE) {
            delete str;
          }
          copyMove(rhs, true);
          return *this;
        }

        ~VariantType() {
          if (dataType == STRING_TYPE) {
            delete str;
          }
        }

        DataType getType() const {
          return dataType;
        }

        uint32_t getU32() const {
          return u32;
        }

        int32_t getI32() const {
          return i32;
        }

        float getFloat() const {
          return fl;
        }

        const String &getString() const {
          return *str;
        }

      private:
        DataType dataType;
        union {
          uint32_t u32;
          int32_t i32;
          float fl;
          String *str;
        };

        void copyMove(VariantType &other, bool move = false) {
          dataType = other.dataType;
          if (move) {
            other.dataType = NO_TYPE;
          }
          switch (dataType) {
            case U32_TYPE:
              u32 = other.u32;
              break;

            case I32_TYPE:
              i32 = other.i32;
              break;

            case FLOAT_TYPE:
              fl = other.fl;
              break;

            case STRING_TYPE:
              if (move) {
                str = other.str;
                other.str = nullptr;
              } else {
                str = new String(*other.str);
              }
              break;

            default:
              break;
          }
        }
    };
    virtual VariantType getValue() const = 0;
};

template<class T>
class TemplateDerived : public BaseClass {
  public:
    TemplateDerived(const T &v): value(v) {
    }

    virtual VariantType getValue() const override {
      VariantType variant {value};
      return variant;
    }

  private:
    T value;
};

BaseClass *baseArray[] = {
  new TemplateDerived<uint32_t>(1000),
  new TemplateDerived<int32_t>(-5000),
  new TemplateDerived<float>(3.14159),
  new TemplateDerived<String>("Hello World")
};

void setup() {
  Serial.begin(115200);
  delay(1000);

  for (auto p : baseArray) {
    BaseClass::VariantType variant = p->getValue();
    switch (variant.getType()) {
      case BaseClass::VariantType::U32_TYPE:
        Serial.println(variant.getU32());
        break;

      case BaseClass::VariantType::I32_TYPE:
        Serial.println(variant.getI32());
        break;

      case BaseClass::VariantType::FLOAT_TYPE:
        Serial.println(variant.getFloat(), 5);
        break;

      case BaseClass::VariantType::STRING_TYPE:
        Serial.println(variant.getString());
        break;

      default:
        break;
    }
  }
}

void loop() {
}
```

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [October 16, 2023, 12:12pm UTC](https://forum.arduino.cc/t/how-to-declare-callback-with-printable-return-type/1116702/17 "2023-10-16T12:12:10Z")

</div>

Closed on October 16, 2023, 12:12pm UTC

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