gpt4 book ai didi

带有可选参数的 C++ 构造函数

转载 作者:行者123 更新时间:2023-12-03 07:14:55 25 4
gpt4 key购买 nike

嗨,我是 C++ 新手,我正在尝试创建一个类层次结构,其中每个类代表架构文档中的一个节点,请考虑 json-schema。看看例如的表示一个string 。一个string可以有三个可选约束

  • min_length
  • max_length
  • pattern

此外还有stringtype所以有一个代表 type 的基类是有意义的所有类型( booleannumber... )都继承自该类型。现在,实现这一目标的一种方法是编写类似

struct Type {
const std::string m_name;

Type(const std::string& name)
: m_name{name}
{}

virtual X Serialize() const {
//...
}
};

struct String : Type {
const int m_max_len;
const int m_min_len;
const std::string m_pattern;

String(int min_len, int max_len, const std::string& pattern)
: Type("string")
, m_min_len(min_len)
, m_max_len(max_len)
, m_pattern(pattern)
{}

X Serialize() const override {
// If min_length was not set then it should be omitted from the serialized output.
}
};

这个 String实现不会使约束变得可选。该怎么办?

选项:

  • 可以采用一种策略,将默认构造函数参数设置为某些“非法”值,例如 INT_MIN (这在这种情况下有效,因为长度不能为负),但这在一般情况下不起作用。很可能所有可能的整数都是合法值,pattern 也是如此。参数。
  • 您不希望对可选参数的每种可能的排列都使用不同的构造函数。在这种情况下,有三个可选值,将产生 2^3不同的构造函数。此外,编译器也不可能区分构造函数 String(int min_length)String(int max_length) .
  • 可以做类似的事情

    String(int* min_length = nullptr, int* max_length = nullptr, const std::string* nullptr)

    但那么你就必须使用 new/delete或给出设置参数的左值。
  • 最后每个成员都可以是std::unique_ptr

    String(std::unique_ptr<int> min_value nullptr, std::unique_ptr<int> max_value = nullptr, std::unique_ptr<const std::string> pattern = nullptr)

    但是当创建 String 的实例时,您最终会得到相当复杂的调用。另外,如果实现 Type 的容器可能有自己的可选参数的东西很快就会失控。

最后,代码必须与 C++14 兼容。

最佳答案

您可以简单地使用std::可选:

String(const std::optional<int> &min_len, const std::optional<int> &max_len, 
const std::optional<std::string> &pattern);

Type *type = new String(5, {}, std::nullptr); // last 2 parameters are omitted.

对于 C++14,您可以使用其他开源库中存在的类似构造(例如 boost::Optionalfolly::Optional)。

关于带有可选参数的 C++ 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64924818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com