vendredi 14 juillet 2017

Clean Instantiation of a Vector in the Base Class

I'm working on code in C++11 and part of the code related to class construction and vector values has gotten out of hand. How can I make this more concise?

My work is related to version and have created a vector of version numbers of type std::vector<uint16_t> to hold an array of values to represent the version of format 1.0.0.25. I would like all classes to have a Version so I placed this in the base class. The children then inherit for Base and instantiate the version.

Currently, my code has a Version class, a Base class, and a Child class. The developer will hardcode the version in by setting the value in a define variable in the Child class. I would like that to be easy to see and read. My issue is that the part where the Child class passes the value is currently very ugly and I'm hoping to make it more concise and readable.

The code is:

#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();
}

And my issue is that while I like have an easy way to see the Version as in #define CHILD_VERSION {1, 0, 0, 25}, the constructor call is incredibly ugly:

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

I would like to do this:

Child() : Base(CHILD_VERSION) {}

But in XCode this results in an error of "No Matching Constructor for initialization of type Base". Because this is valid syntax:

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

I'm unsure why the short Base(CHILD_VERSION) doesn't work in c++11.

How can I shorten this?

Aucun commentaire:

Enregistrer un commentaire