Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
63 views
in Technique[技术] by (71.8m points)

c++ - 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.

question from:https://stackoverflow.com/questions/65893131/how-to-ignore-template-parameters-for-hashmap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...