Warning: include_once(/var/www/web/../var/bootstrap.php.cache): failed to open stream: No such file or directory in /var/www/web/app.php on line 11

Warning: include_once(): Failed opening '/var/www/web/../var/bootstrap.php.cache' for inclusion (include_path='.:') in /var/www/web/app.php on line 11

Warning: session_cache_limiter(): Cannot change cache limiter when headers already sent in /var/www/var/cache/prod/classes.php on line 91

Warning: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time in /var/www/var/cache/prod/classes.php on line 91

Warning: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time in /var/www/var/cache/prod/classes.php on line 203

Warning: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time in /var/www/var/cache/prod/classes.php on line 203

Warning: session_set_save_handler(): Cannot change save handler when headers already sent in /var/www/var/cache/prod/classes.php on line 222
Rogiel.com — Blog — Storing multiple templates specializations inside a container

C++ templates gives us, the developers, a great way to create containers and generic classes that can support a type-safe environment. Everything is good, until the time comes and you want to store multiple template specialisations inside a single containter class.

Say you have a template named MyTemplatedClass and you want to store multiple specialisations of the template inside a vector:

template<typename T>
class MyTemplatedClass {
public:
    void print();
}

std::vector<MyTemplatedClass*> myVector; // <--- won't compile!

As a first solution we could add more vectors, one for every template specialisations, even though it would work at a small scale, as soon as you begin to have more and more speacializations, it's a no-go.

Another solution would be for you to have a non-templated base class in which the template would extend.

// it's not a template!
class MyBaseClass {
public:
    virtual void print() = 0; // pure-virtual
};

// MyTemplatedClass extends MyBaseClass
template<typename T>
class MyTemplatedClass : public MyBaseClass {
private:
    T value;
public:
    MyTemplatedClass(T value) : value(value) {};

    virtual void print() {
        std::cout << value << std::endl;
    }
};

std::vector<MyBaseClass*> myVector; // <--- this will compile! Great!

Great! Problem solved! If you don't believe me check this Ideone