A
A
aminought2016-09-17 02:48:38
C++ / C#
aminought, 2016-09-17 02:48:38

How to organize dependency injection and template usage in C++?

There is something like this code:

struct Object {}

template<class Img>
class IImageRecognizer {
public:
    virtual ~IImageRecognizer() {}
    virtual Object recognize(Img* img) = 0;
}

template<class Img>
class OpenCVRecognizer: public IImageRecognizer<Img> {
public:
    Object recognize(Img* img);
}

class App {
public:
    App(IImageRecognizer<cv::Mat>* recognizer);
private:
    IImageRecognizer<cv::Mat>* recognizer;
}

...
IImageRecognizer<cv::Mat>* recognizer = new OpenCVRecognizer<cv::Mat>();
App* app = new App(recognizer);

There may be minor flaws, since the code was written on the knee. In general, the problem is immediately visible here: the App class should not know anything about the internal implementation of the class responsible for image recognition, but in this case it has information that the class uses cv::Mat. In general, in this case, I use templates so that different parameters can be passed to the recognize method in different subclasses, but something went wrong. What is the best way to organize this kind of code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2016-09-17
@aminought

Templates are not needed here. You can introduce your own UniversalImage image class, which automatically converts images between all used formats and produces the desired one:

class UniversalImage {
    boost::variant<cv::Mat, AnotherImage> internalImg_;
public:
    UniversalImage(const cv::Mat& img);
    UniversalImage(const AnotherImage& img);
    cv::Mat asCVMat() const;
    AnotherImage asAnotherImage() const;
};

With the help of this UniversalImage it will be possible to come up with a hierarchy of image handlers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question