Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yshui/e02c08ab2f2b1ef8fa77 to your computer and use it in GitHub Desktop.
Save yshui/e02c08ab2f2b1ef8fa77 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 -------------
#include <iostream>
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);
std::cout << rhs->value << "\n";
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 padding[10000];
T value;
};
struct FII2 : FooInterface {
FooInterface* Add(FooInterface *rhs) override {
return 0;
}
bool Equal(FooInterface *rhs) override {
return false;
}
};
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));
}
FII2 a;
FooInterfaceImpl<int> b(0);
std::cout << "Foo(b, a) = " << Foo(&b, &a) << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment