Skip to content

Instantly share code, notes, and snippets.

@radicaljims
Last active March 2, 2019 05:01
Show Gist options
  • Save radicaljims/3143edbddfc45b4b0a5414b139623678 to your computer and use it in GitHub Desktop.
Save radicaljims/3143edbddfc45b4b0a5414b139623678 to your computer and use it in GitHub Desktop.
C++ has unnamed classes!
clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
The message is 1 `action` 2 is 3
The (int) sum is 3
The message is 3.000000 `action` 2.000000 is 1.000000
The (float) difference is 1
#include <iostream>
#include <string>
#include <functional>
template<typename T>
class Contact
{
public:
virtual ~Contact() {}
virtual void Message(std::string) = 0;
virtual void Report(T) = 0;
};
using IntAction = std::function<int(int, int)>;
using FltAction = std::function<float(float, float)>;
template<typename B, typename A, typename C>
class Machine
{
public:
Machine(C c_) : c(c_)
{}
void actionAndReport(B n, B m, A a)
{
c.Message(std::to_string(n) + " `action` " +
std::to_string(m) + " is " + std::to_string(a(n, m)));
c.Report(a(n, m));
}
C c;
};
using Messenger = std::function<void(std::string)>;
using IntReporter = std::function<void(int)>;
using FltReporter = std::function<void(float)>;
template<typename I, typename R>
auto make_contact_shim(Messenger m, R r)
{
class : Contact<I> {
public:
void Message(std::string s) override
{
m(s);
}
void Report(I i) override
{
r(i);
}
Messenger m;
R r;
} c;
c.m = m;
c.r = r;
return c;
}
int main() {
auto c = make_contact_shim<int, IntReporter>(
[=](std::string s)
{
std::cout << "The message is " << s << std::endl;
},
[=](int i)
{
std::cout << "The (int) sum is " << i << std::endl;
}
);
Machine<int, IntAction, decltype(c)> machine(c);
machine.actionAndReport(1, 2, [=](int a, int b)
{
return a + b;
});
auto c2 = make_contact_shim<float, FltReporter>(
[=](std::string s)
{
std::cout << "The message is " << s << std::endl;
},
[=](float i)
{
std::cout << "The (float) difference is " << i << std::endl;
}
);
Machine<float, FltAction, decltype(c2)> machine2(c2);
machine2.actionAndReport(3.0, 2.0, [=](float a, float b)
{
return a - b;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment