Created
May 7, 2019 01:01
-
-
Save matutter/e856f238dcbfd04058be98116ad08967 to your computer and use it in GitHub Desktop.
How a C++ factory pattern may be applied to subclasses using some static methods.
This file contains hidden or 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 <vector> | |
class Base { | |
public: | |
Base() {} | |
virtual int func() = 0; | |
}; | |
class Sub1 : public Base { | |
public: | |
using Base::Base; | |
int func() override { return 1; }; | |
static Base* create() { return new Sub1(); } | |
static bool check() { return false; } | |
}; | |
class Sub2 : public Base { | |
public: | |
using Base::Base; | |
int func() { return 2; }; | |
static Base* create() { | |
return new Sub2(); | |
} | |
static bool check() { | |
return true; | |
} | |
}; | |
void dobase(Base* b) { | |
std::cout << b->func() << std::endl; | |
} | |
int main(void) { | |
Sub1 s1; | |
Base* s2 = Sub2::create(); | |
std::vector<Base*> v({ | |
&s1, s2 | |
}); | |
for ( auto it: v ) { | |
std::cout << it->func() <<std::endl; | |
} | |
// pretty easy to make a factory around this | |
std::vector<std::pair<Base* (*)(), bool (*)()>> chooser( | |
{std::make_pair(Sub2::create, Sub2::check), | |
std::make_pair(Sub1::create, Sub1::check)}); | |
for (auto it : chooser) { | |
if ( it.second() ) { | |
Base* b = it.first(); | |
dobase(b); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better examples here https://stackoverflow.com/questions/5450742/is-it-possible-in-c-to-loop-over-all-subclasses-of-an-abstract-class