Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.