Last active
September 5, 2024 13:25
-
-
Save sim642/4525268 to your computer and use it in GitHub Desktop.
C++11 variadic template class for C# equivalent of delegates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef DELEGATE_HPP_INCLUDED | |
#define DELEGATE_HPP_INCLUDED | |
#include <functional> | |
#include <vector> | |
// general case | |
template<typename R, typename... Args> | |
class delegate | |
{ | |
public: | |
template<typename U> | |
delegate& operator += (const U &func) | |
{ | |
funcs.push_back(std::function<R(Args...)>(func)); | |
return *this; | |
} | |
std::vector<R> operator () (Args... params) | |
{ | |
std::vector<R> ret; | |
for (auto f : funcs) | |
{ | |
ret.push_back(f(params...)); | |
} | |
return ret; | |
} | |
private: | |
std::vector<std::function<R(Args...)>> funcs; | |
}; | |
// specialization when return type is void | |
template<typename... Args> | |
class delegate<void, Args...> | |
{ | |
public: | |
template<typename U> | |
delegate& operator += (const U &func) | |
{ | |
funcs.push_back(std::function<void(Args...)>(func)); | |
return *this; | |
} | |
void operator () (Args... params) | |
{ | |
for (auto f : funcs) | |
{ | |
f(params...); | |
} | |
} | |
private: | |
std::vector<std::function<void(Args...)>> funcs; | |
}; | |
#endif // DELEGATE_HPP_INCLUDED |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "delegate.hpp" | |
using namespace std; | |
int main() | |
{ | |
delegate<void, int, int> d1; | |
d1 += [](int x, int y){cout << x + y << endl;}; | |
d1 += [](int x, int y){cout << x * y << endl;}; | |
d1(3, 5); | |
delegate<int, int, int> d2; | |
d2 += [](int x, int y){return x + y;}; | |
d2 += [](int x, int y){return x * y;}; | |
for (auto ret : d2(3, 5)) | |
{ | |
cout << ret << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment