Created
September 13, 2015 21:39
-
-
Save lucasdemarchi/492b093f21bde064e848 to your computer and use it in GitHub Desktop.
downcast example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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