Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <memory>
- #include <typeinfo>
- #include <vector>
- namespace {
- using std::bad_cast;
- using std::cout;
- using std::make_unique;
- using std::unique_ptr;
- using std::vector;
- struct B { virtual void method() const = 0; virtual ~B() = default; };
- struct D1 : public B { void method() const override { cout << "D1\n"; } };
- struct D2 : public B { void method() const override { cout << "D2\n"; } };
- }
- int main() {
- const vector<unique_ptr<B>> objects{[] {
- vector<unique_ptr<B>> objects;
- objects.reserve(2);
- objects.push_back(make_unique<D2>());
- objects.push_back(make_unique<D1>());
- return objects;
- }()};
- for (const auto& object_ptr : objects) {
- if (const auto *const ptr{dynamic_cast<D1*>(object_ptr.get())}; ptr) {
- cout << "Successfully cast pointer to D1*; calling method(): ";
- ptr->method();
- } else {
- cout << "Failed to cast pointer to D1*; calling method(): ";
- object_ptr->method();
- }
- try {
- const auto &ref{dynamic_cast<D1&>(*object_ptr)};
- cout << "Successfully cast reference to D1&; calling method(): ";
- ref.method();
- } catch (const bad_cast&) {
- cout << "Failed to cast reference to D1&; calling method(): ";
- object_ptr->method();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement