user5448913
user5448913

Reputation:

Generic parameter checker in C++

I am working on a generic parameter checker in C++ that can add options and parse their content.

Here is my Param class:

class Param
{
public:
  Param();
  ~Param();

  template <typename T>
  void  add_option(std::string, std::string, T&); // flag, description, storage value

protected:
  std::map<std::string, IOption> options;
};

template <typename T>
void    Param::add_option(std::string, std::string, T&) // Is templated to add an option depending on its type
{}

template<> void Param::add_option<int>(std::string, std::string, int &);
template<> void Param::add_option<std::string>(std::string, std::string, std::string &);

As you can see I wish to store up new options in a map, here is the class Option and it's "interface":

template <typename T>
class Option : public IOption
{
public:
  Option(std::string flag, std::string desc, T &ref) : flag_(flag), desc_(desc), ref_(ref) {}
  ~Option() {}

  std::string getFlag()
  {
    return (flag_);
  }

protected:
  std::string   flag_;
  std::string   desc_;
  T             &ref_;
};

class IOption
{
public:
  virtual ~IOption() {}
  IOption() {}

  virtual std::string getFlag() = 0;
};

The reason why I have created this interface is to store up my options in the map even though they are templated.

But right now, I can't compile because

field type 'IOption' is an abstract class

What would be the best way to create a generic parameter checker from what I have in C++?

Upvotes: 1

Views: 66

Answers (2)

dtopham75
dtopham75

Reputation: 620

The map class needs to allocate storage for the key / value pairs you add to it. By definition you can't instantiate an instance of an abstract class, so the storage size cannot be determined.

So yes, store pointers or smart pointers to IOption.

Upvotes: 1

user2807083
user2807083

Reputation: 2982

You can't store instance of abstract class. You should use pointer or smart pointer and change options declaration like this:

std::map<std::string, IOption*> options;

or

std::map<std::string, std::unique_ptr<IOption> > options;

or

std::map<std::string, std::shared_ptr<IOption> > options;

Upvotes: 3

Related Questions