Skip to content

linkouille/CppCalback

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

C++ Callback

Library aiming to add callbacks that are simple to use, fast and allocation free in C++. Callbacks are single cast delegate to which you can bind at runtime generic function, class method and lambda expression. The header uses no external dependencies, only C++20.

Instalation:

You just need to add Callback.hpp to your project and include it.

The project use premake if you want to launch it generate.bat for windows, and then launch the vs2022 project.

Usage:

This repo is an example project, you can find use case in main.cpp. The following can be found in main.cpp.

Generic function:

Let's take an example function foo:

int foo(int id) 
{
    printf("foo : %d \n", id);
    return 1;
}

Create a callback and bind it foo :

// Create a callback that return a int and take a single int as parameter
Callback<int, int> actionGeneric;
// Bind foo to the callback
actionGeneric = Callback<int, int>::Bind<foo>();

Invoke callback:

int output = actionGeneric(0);
// output = 1
// stdout : "foo : 0"

Class Method:

Let's take an example class :

class Cat
{
public:
    const char* name;

    Cat(const char* pName) : name(pName) {}

    void Miaou() {
        printf("%s miaou\n", name);
    }

};

Create a callback and bind it Miaou method :

Cat ganon("Ganon");

// Create a callback that return void and take no parameter
Callback<void> actionClass;
// Bind the Miaou method from ganon, an instance of the Cat class
actionClass = Callback<void>::Bind<Cat, &Cat::Miaou>(&ganon);

Invoke callback:

actionClass();
// stdout : "Ganon miaou"

Lambda

Create a callback and bind it a lambda expression :

int contextCount = 1;

Callback<int, int> actionLambda;

// Create a callback that return a int and take a int as parameter
actionLambda = Callback<int, int>::Bind([&contextCount](int p) -> int
{ 
    printf("Hello from lambda, context : %d, parameter %d\n", contextCount, p); 
    return 2;
});

Invoke callback:

actionLambda(2);
// stdout : "Hello from lambda, context : 1, parameter 2"

Contact:

@koukouil300 - @kuroneko300.bsky.social

mail : feugeassimon@gmail.com

About

Fast C++ singlecast delegate

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published