Skip to content

Instantly share code, notes, and snippets.

@sim642
Last active July 22, 2020 17:27
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sim642/4525268 to your computer and use it in GitHub Desktop.
Save sim642/4525268 to your computer and use it in GitHub Desktop.
C++11 variadic template class for C# equivalent of delegates.
#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
#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