A very tiny C++ wrapper for callable object without any heap memory or exception.
It is used in the same way as std::function.
- normal function
#include "embed_function.hpp"
#include <cstdio>
void print_num(int num) { printf("hello %d", num); }
int main()
{
embed::function<void(int)> fn = print_num;
fn(123);
return 0;
}
- lambda function
#include "embed_function.hpp"
#include <iostream>
int main()
{
embed::function<void()> fn = []() { std::cout << "hello world" << std::endl; };
fn();
return 0;
}
- callable object
#include "embed_function.hpp"
#include <iostream>
#include <string>
struct Test
{
std::string str;
void operator()() const
{
std::cout << this->str << std::endl;
}
};
int main()
{
Test t{"hello world"};
embed::function<void(), sizeof(std::string)> fn = t;
fn();
return 0;
}
- Normal function
#include "embed_function.hpp"
#include <cstdio>
void print_num(int num) { printf("hello %d", num); }
int main()
{
// The type of fn is embed::function<void(int)>
auto fn = embed::make_function(print_num);
fn(123);
return 0;
}
- lambda function
#include "embed_function.hpp"
#include <iostream>
int main()
{
// The type of fn is embed::function<void()>
auto fn = embed::make_function(
[]() { std::cout << "hello world" << std::endl; });
fn();
return 0;
}
- callable object
#include "embed_function.hpp"
#include <iostream>
#include <string>
struct Test
{
std::string str;
void operator()() const
{
std::cout << this->str << std::endl;
}
};
int main()
{
Test t{"hello world"};
// The type of fn is embed::function<void()>
auto fn = embed::make_function(t);
fn();
return 0;
}