Skip to content

Instantly share code, notes, and snippets.

@matutter
Created May 7, 2019 01:01
Show Gist options
  • Save matutter/e856f238dcbfd04058be98116ad08967 to your computer and use it in GitHub Desktop.
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.
#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