基类中向量的干净实例化

Clean Instantiation of a Vector in the Base Class

本文关键字:实例化 向量 基类      更新时间:2023-10-16

我正在处理 C++11 中的代码,与类构造和向量值相关的部分代码已经失控。如何使它更简洁?

我的工作与版本有关,并创建了一个类型为std::vector<uint16_t>的版本号向量来保存一个值数组来表示格式1.0.0.25的版本。我希望所有类都有一个版本,所以我把它放在基类中。然后,子项继承Base并实例化版本。

目前,我的代码有一个版本类、一个基类和一个子类。开发人员将通过在 Child 类的定义变量中设置值来硬编码版本。我希望它易于查看和阅读。 我的问题是 Child 类传递值的部分目前非常丑陋,我希望让它更加简洁易读。

代码为:

#include <vector>
namespace CodeStuff
{
namespace VersionStuff
{

typedef uint16_t VersionType;
class Version
{
public:
Version(const std::vector<VersionType> & aNumbers, const VersionType aType = -1)
{
numbers_ = aNumbers;
type_ = aType;
}
private:
std::vector<VersionType> numbers_;
VersionType type_;
};
} // end namespace VersionStuff
} // end namespace CodeStuff
class Base
{
public:
Base(const CodeStuff::VersionStuff::Version & aVersion) : version_(aVersion)
{
}
const CodeStuff::VersionStuff::Version getVersion() const {return version_;}
private:
const CodeStuff::VersionStuff::Version version_;
};

#define CHILD_VERSION {1, 0, 0, 25}
class Child : public Base
{
public:
Child() : Base(CodeStuff::VersionStuff::Version{std::vector<CodeStuff::VersionStuff::VersionType>{CHILD_VERSION}}) {}
};

int main(int argc, const char * argv[]) {
Child myChild();
}

我的问题是,虽然我喜欢有一种简单的方法来查看#define CHILD_VERSION {1, 0, 0, 25}中的版本,但构造函数调用非常丑陋:

Child() : Base(CodeStuff::VersionStuff::Version{std::vector<CodeStuff::VersionStuff::VersionType>{CHILD_VERSION}}) {}

我想这样做:

Child() : Base(CHILD_VERSION) {}

但在 XCode 中,这会导致"初始化类型 Base 没有匹配的构造函数"的错误。因为这是有效的语法:

std::vector<uint16_t> v({1, 0 ,0 ,25}); 

我不确定为什么短Base(CHILD_VERSION)在 c++11 中不起作用。

如何缩短此时间?

我最近处理了这样的事情,我没有传递向量,而是使用std::initializater_list作为我获得简单常量版本号的途径。 下面是一个示例:

class Version {
std::vector<unsigned> version;
public:
Version(const std::string & s);
Version(std::initializer_list<unsigned> list) : version(list) {}
bool operator== (const Version & other) const {
return version == other.version;
}
bool operator< (const Version & other) const {
return version < other.version;
}
};

在这里可以像这样创建一个版本:

Version v{1, 0 ,0 ,25};

也可以使基类具有std::initializer_list构造函数,并将其传递给version_对象。