Last active
February 1, 2021 18:37
-
-
Save derrickturk/56b061a96e4d246832a5831af30b2da6 to your computer and use it in GitHub Desktop.
sidecasting with dynamic_cast in C++
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 <iostream> | |
#include <memory> | |
#include <vector> | |
struct base { | |
virtual ~base() = default; | |
}; | |
struct capability1 { | |
virtual void do_capability1() = 0; | |
}; | |
struct capability2 { | |
virtual void do_capability2() = 0; | |
}; | |
template<class T> | |
struct capability3 { | |
virtual void do_capability3(T x) = 0; | |
}; | |
struct A : base, capability1 { | |
void do_capability1() { std::cout << "A capability1\n"; } | |
}; | |
struct B : base, capability2 { | |
void do_capability2() { std::cout << "B capability2\n"; } | |
}; | |
struct C : base, capability1, capability2 { | |
void do_capability1() { std::cout << "C capability1\n"; } | |
void do_capability2() { std::cout << "C capability2\n"; } | |
}; | |
struct D : base, capability3<int> { | |
void do_capability3(int x) | |
{ | |
std::cout << "D capability3 with: " << x << '\n'; | |
} | |
}; | |
struct E : base, capability3<int>, capability3<const char*> { | |
void do_capability3(int x) | |
{ | |
std::cout << "E capability3 with: " << x << '\n'; | |
} | |
void do_capability3(const char* x) | |
{ | |
std::cout << "E capability3 with: " << x << '\n'; | |
} | |
}; | |
int main() | |
{ | |
std::vector<std::unique_ptr<base>> objs; | |
objs.emplace_back(std::make_unique<A>()); | |
objs.emplace_back(std::make_unique<B>()); | |
objs.emplace_back(std::make_unique<C>()); | |
objs.emplace_back(std::make_unique<D>()); | |
objs.emplace_back(std::make_unique<E>()); | |
for (const auto& p : objs) { | |
if (auto* c1 = dynamic_cast<capability1*>(p.get())) { | |
c1->do_capability1(); | |
} | |
if (auto* c2 = dynamic_cast<capability2*>(p.get())) { | |
c2->do_capability2(); | |
} | |
if (auto* c3i = dynamic_cast<capability3<int>*>(p.get())) { | |
c3i->do_capability3(45); | |
} | |
if (auto* c3s = dynamic_cast<capability3<const char*>*>(p.get())) { | |
c3s->do_capability3("hello"); | |
} | |
if (auto* c3d = dynamic_cast<capability3<double>*>(p.get())) { | |
c3d->do_capability3(47.8); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment