1

I came across a class that implements a kind of "strategy pattern" with a concrete implementation defined inside the main class as a template method.

#include <iostream>

struct ObjA { int a = 123; };

struct ObjB { int b = 456; };

class Algo { public: void stratA(const ObjA& obj) { strat<ObjA>(obj); }; void stratB(const ObjB& obj) { strat<ObjB>(obj); }; private: template<typename T> void strat(const T& obj) { std::cout << "Start" << std::endl; print<T>(obj); std::cout << "End" << std::endl; }

template&lt;typename T&gt;
void print(const T&amp; obj);

};

template<> void Algo::print(const ObjA& obj) { std::cout << obj.a << std::endl; }

template<> void Algo::print(const ObjB& obj) { std::cout << obj.b << std::endl; }

int main() { Algo algo; ObjA a; ObjB b; algo.stratA(a); algo.stratB(b);

return 0;

}

Is it a known pattern of should this be considered bad practice?

The strategies and their usage being known at compile time, the main goal I guess is to avoid indirection and hide template abstraction to the user of Algo class.

Delgan
  • 376

0 Answers0