Created
July 26, 2012 22:48
-
-
Save jl2/3185051 to your computer and use it in GitHub Desktop.
An interesting mixin "pattern" using inheritance from a template base class.
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> | |
// A templated abstract base class indicating that all subclasses will have a "load" method, but the parameter type will vary | |
template <class T> class Loadable { | |
public: | |
virtual bool load(const T &ival)=0; | |
}; | |
// A subclass that's loadable from an integer | |
class SubOne : public Loadable<int> { | |
public: | |
SubOne() : _ival(0) {} | |
virtual bool load(const int &ival) { | |
_ival = ival; | |
} | |
friend std::ostream& operator<< (std::ostream &out, SubOne &val); | |
private: | |
int _ival; | |
}; | |
std::ostream& operator<< (std::ostream &out, SubOne &val) { | |
out << val._ival; | |
return out; | |
} | |
// A subclass that's loadable from a float and also contains a SubOne | |
class SubTwo : public Loadable<float> { | |
public: | |
SubTwo() : _fval(0.0) {} | |
virtual bool load(const float &ival) { | |
_fval = ival; | |
_soVal.load(int(ival)); | |
} | |
friend std::ostream& operator<< (std::ostream &out, SubTwo &val); | |
private: | |
float _fval; | |
SubOne _soVal; | |
}; | |
std::ostream& operator<< (std::ostream &out, SubTwo &val) { | |
out << "{" << val._fval << ", " << val._soVal << "}"; | |
return out; | |
} | |
int main(int argc, char *argv[]) { | |
int answer = 42; | |
float pi = 3.141592654; | |
SubOne sone; | |
SubTwo stwo; | |
// Create a | |
sone.load(answer); | |
std::cout << "sone: " << sone << "\n"; | |
stwo.load(pi); | |
std::cout << "stwo: " << stwo << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment