std::function!?

Hello,
I have a program that works on computer that takes in a class through a template and puts a function from it into a vector to use later, but I need to use std::funciton.
arduinoSTL has functional, but it does not have the std::function in it? How can I use it to do this?

code

#include <Streaming.h>
#include <ArduinoSTL.h>

using namespace std;

struct typeA
{
public:
	int data = 0;

	void update()
	{
		Serial << "hello, my data is " << data << "\n";
	}
};

struct typeB
{
	float data = 0;

	void update()
	{
		Serial << "hi, my data is " << data << "\n";
	}
};


class typeList
{
	std::vector<std::function<void()>> items; //This does not work
public:

	template <class Item>
	void addItem(Item& item)
	{
		// Care: life time of item should be bigger than this instance
		items.push_back([&]() { item.update(); });
	}

	void doWork()
	{
		for (auto& f : items) //As a result neither does this
		{
			f();
		}
	}
};


int main()
{
	typeA aThing;
	typeB bThing;
	typeList listThings;

	aThing.data = 128;
	bThing.data = -3.234;

	listThings.addItem(aThing);
	listThings.addItem(bThing);
	listThings.doWork();

	return 0;
}


void setup()
{
	Serial.begin(115200);
  /* add setup code here */
	
}

void loop()
{
	main();
  /* add main program code here */

}
1 Like

Why do you think you need to do this? How many classes are there going to be on the Arduino? How many instances of the classes? How many functions do you need to keep track of?

Does it even compile with a function called main()? If it does, then it's overwriting the built-in Arduino main() function and your code will never call setup() or loop().

At the time that I was writing that I did not know that std::function actually creates a 'dynamic function' (dynamic memory) (Or why dynamic memory is bad on an arduino), so it probably should not be done. The code's eventual purpose was to have objects of some types (for a gui) that could be added to 1 single object that would call an update function to create a 'layer' so I could update all the objects by only calling 1 function.