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<typename T>
    void print(const T& 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.

1
  • 1
    Aside: you could make strat public, stratA and stratB aren't needed because template arguments can be deduced
    – Caleth
    Oct 13, 2022 at 13:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.