Skip to content

Instantly share code, notes, and snippets.

@lucasdemarchi
Created September 13, 2015 21:39
Show Gist options
  • Save lucasdemarchi/492b093f21bde064e848 to your computer and use it in GitHub Desktop.
Save lucasdemarchi/492b093f21bde064e848 to your computer and use it in GitHub Desktop.
downcast example
#include <type_traits>
#define DOWNCAST_METHOD(name_, Base_, Derived_) \
template <typename Base_> \
static Derived_ *from(Base_ *base_) { \
static_assert(std::is_base_of<Base_, Derived_>::value, \
"method from() requires base object as argument"); \
return static_cast<Derived_*>(base_); \
}
class A {
};
class B : public A {
public:
DOWNCAST_METHOD(from, A, B)
};
class C {
};
class D : public C {
public:
DOWNCAST_METHOD(from, C, D)
};
int main()
{
B b;
A *a = &b;
B *x = B::from(a);
// error
//C *x = B::from(a);
// error
//C *c = D::from(a);
// error
//C *c = D::from(&b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment