Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class Result{};
- class A {};
- class B {
- public:
- void specific() const
- {
- std::cout << "B::specific()" << std::endl;
- };
- };
- class C : public B {};
- class D {};
- template<class Type>
- class RelationshipWithA
- {
- const A& a_;
- const Type& t_;
- public:
- typedef Type target_type;
- RelationshipWithA (const A& a, const Type& t)
- :
- a_(a),
- t_(t)
- {
- std::cout << "RelationshipWithA::ctor" << std::endl;
- };
- const A& a() const
- {
- return a_;
- }
- const Type& type() const
- {
- return t_;
- }
- };
- class DefaultAlgorithm
- {
- public:
- template <class Relationship>
- void calculate (Result& res, const Relationship& r)
- {
- std::cout << "DefaultAlgorithm::calculate" << std::endl;
- const A& a = r.a();
- const typename Relationship::target_type& t = r.type();
- // Default iterator based calculation on a, target_type and r
- };
- };
- class AlternativeAlgorithm
- :
- public DefaultAlgorithm
- {
- public:
- template <class Relationship>
- void calculate (Result& res, const Relationship& r)
- {
- std::cout << "AlternativeAlgorithm::calculate" << std::endl;
- // Optimized iterator based calculation on a, target_type and r
- }
- };
- class ImplementationBasedAlgorithm
- :
- public DefaultAlgorithm
- {
- public:
- // No specialization: Relationships store
- // a const reference to any class that inherits from B
- template <class Relationship>
- void calculate (Result& res, const Relationship& r)
- {
- // Use B implementation and the Relationship With A to compute the result
- std::cout << "ImplementationBasedAlgorithm::calculate" << std::endl;
- const A& a = r.a();
- const B& b = r.type();
- b.specific();
- // Implementation based on B implementation
- }
- };
- int main(int argc, const char *argv[])
- {
- Result res;
- A a;
- C c;
- RelationshipWithA<C> relationshipAC (a, c);
- DefaultAlgorithm defaultAlg;
- AlternativeAlgorithm alternativeAlg;
- ImplementationBasedAlgorithm implementationAlg;
- defaultAlg.calculate(res, relationshipAC);
- alternativeAlg.calculate(res, relationshipAC);
- implementationAlg.calculate(res,relationshipAC);
- D d;
- RelationshipWithA<D> relationshipAD (a, d);
- defaultAlg.calculate(res, relationshipAD);
- alternativeAlg.calculate(res, relationshipAD);
- // This fails, as expected
- //implementationAlg.calculate(res,relationshipAD);
- return 0;
- }
- DefaultAlgorithm algo = Factory.CreateImplementationBasedAlgorithm();
- RelationshipWithA<D> relationshipAD (a, d);
- algo.calculate(res, relationshipAD); //won't fail because the base class methods are used (because it isn't virtual)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement