c++ - C++ 中的通用参数检查器

标签 c++ parameters

我正在使用 C++ 开发一个通用参数检查器,它可以添加选项并解析它们的内容。

这是我的 Param 类:

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

如您所见,我希望在 map 中存储新选项,这里是 Option 类,它是“接口(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;
};

我创建这个界面的原因是为了在 map 中存储我的选项,即使它们是模板化的。

但是现在,我无法编译,因为

field type 'IOption' is an abstract class

从我的 C++ 中创建通用参数检查器的最佳方法是什么?

最佳答案

您不能存储抽象类的实例。您应该使用指针或智能指针并像这样更改 options 声明:

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

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

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

关于c++ - C++ 中的通用参数检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939254/

相关文章:

c++ - "Only static constant integral variables may be initialized within a class "

C++读取txt文件的CSV值

C++ 继承和多态未知输出

c++ - 相同代码在不同设备上的不同行为

rest - 使用 or 条件定义查询参数的 RESTful 最佳实践是什么?

c++ - 读取一个值并使用它而不用声明一个额外的变量,就像在 Java 的 sc.next() 中一样

windows - 相当于带引号的 Unix 参数扩展的批处理文件

parameters - 具有可选参数的冲突重载方法

Spring 和 jtds.jdbc.Driver 参数

class - 关于 Clojure 中的列表和其他内容的问题