Skip to content

Instantly share code, notes, and snippets.

@timshen91
Last active October 11, 2015 21:08
Show Gist options
  • Save timshen91/aa8bb6198b3976582762 to your computer and use it in GitHub Desktop.
Save timshen91/aa8bb6198b3976582762 to your computer and use it in GitHub Desktop.
//template<typename T>
//bool Foo(T a, T b) {
// T c = a + b;
// return a == c;
//}
//
//Expands to:
//------------- begin -------------
class FooInterface {
public:
virtual ~FooInterface() {}
// Caller ensures that `this` and rhs have the same dynamic type.
virtual FooInterface* Add(FooInterface* rhs) = 0;
virtual bool Equal(FooInterface* rhs) = 0;
};
template<typename T>
struct FooInterfaceImpl : FooInterface {
FooInterfaceImpl(const T& v) : value(v) {}
FooInterface* Add(FooInterface* rhs_i) override {
auto rhs = static_cast<FooInterfaceImpl<T>*>(rhs_i);
return new FooInterfaceImpl(value + rhs->value);
}
bool Equal(FooInterface* rhs_i) override {
auto rhs = static_cast<FooInterfaceImpl<T>*>(rhs_i);
return value == rhs->value;
}
T value;
};
bool Foo(FooInterface* a, FooInterface* b) {
FooInterface* c = a->Add(b);
return a->Equal(c);
}
//------------- end -------------
#include <cassert>
int main() {
{
FooInterfaceImpl<int> a(3), b(4);
assert(!Foo(&a, &b));
}
{
FooInterfaceImpl<int> a(3), b(0);
assert(Foo(&a, &b));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment