HennyKo
HennyKo

Reputation: 772

How to "ignore" template parameters for hashmap?

Coming from a non statically typed language I sometimes struggle with type constrains.

I am looking for a way to store all my objects in a hashmap. The problem is, that the parent class uses templates as some children classes return different size and type of arrays.

template<typename T, std::size_t Size>
class Module {
 public:
  virtual std::array<T, Size> getValues() = 0;
};

class SwitchModule : public Module<bool, 2> {
  std::array<bool, 2> getValues() override;
};

class TemperatureModule : public Module<float, 4> {
  std::array<float, 4> getValues() override;
};

This all works fine, until I want to add all my SwitchModules and TemperatureModules to a hash map. As I have to use the base class for the hash map the compiler expects me to provide T and Size. This does not work:

std::unordered_map<std::string, Module> modulesMap;

Is there a clever workaround how to save SwitchModule and TemperatureModule in an unordered_map? Thank you.

Upvotes: 0

Views: 76

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

You could add a base class and store pointers to that in your map:

class ModuleBase {
public:
    virtual ~ModuleBase() = default;
};

template<typename T, std::size_t Size>
class Module : public ModuleBase {
 public:
  virtual std::array<T, Size> getValues() = 0;
};
#include <memory>

// ...

    std::unordered_map<std::string, std::unique_ptr<ModuleBase>> modulesMap;

    modulesMap.emplace("foo", std::make_unique<SwitchModule>());
    modulesMap.emplace("bar", std::make_unique<TemperatureModule>());

Upvotes: 1

Related Questions