Skip to content

A very tiny C++ wrapper for callable objects without using heap, which is used in the same way as std::function.

License

Notifications You must be signed in to change notification settings

Kim-J-Smith/embed-function

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

embed-function

Version - 1.0.4 License - MIT c++ - 11/14/17/20

gcc-c++11/14/17/20/23 - passing clang-c++11/14/17/20/23 - passing msvc-c++14/17/20/23 - passing

A very tiny C++ wrapper for callable object without any heap memory or exception. It is used in the same way as std::function.


Basic Usage

  • 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;
}

Use embed::make_function

  • 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;
}

About

A very tiny C++ wrapper for callable objects without using heap, which is used in the same way as std::function.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published