我正在处理 C++11 中的代码,与类构造和向量值相关的部分代码已经失控。我怎样才能使这个更简洁?
我的工作与 version 相关,并创建了一个 type 版本号向量std::vector<uint16_t>
来保存一组值来表示 format 的版本1.0.0.25
。我希望所有的类都有一个版本,所以我把它放在基类中。然后子代继承Base
并实例化版本。
目前,我的代码有一个 Version 类、一个 Base 类和一个 Child 类。开发人员将通过在 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_
对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句