Salamandar Salamandar - 1 year ago 73
C++ Question

c++ - Initialize objects inside vector declaration

I'm writing a small command-line parsing library and you can describe options statically :

std::vector<Args::Descriptor> description{
{UNKNOWN, 0,'h' , "help", Args::None, "print this help"}

where in my lib,

struct Descriptor {
const uint option;
const int type;
const char shortopt;
const char* const longopt;
const CheckArg check_arg; // Function pointer
const char* help;

Then the Descriptor is used to initialize a class :

Option(const Descriptor *descriptor)
{ … }

Could I remove my Descriptor structure by initializing the Options class inside the vector ?

std::vector<Args::Option> options{
{UNKNOWN, 0,'h' , "help", Args::None, "print this help"}

What signature should my Option constructor have ? Assuming the Descriptor class completely disappears from the code to simplify it.

Thanks a lot :D

Answer Source

This will not work. Option's constructor's argument is a pointer to a Descriptor. That Descriptor has to come from somewhere. You cannot initialize a pointer to a class with an instance of the class itself.

What you can do, though, is construct a vector of Descriptors exactly how you are doing it now.

Then, initialize your Option vector with pointers to the individual values in your Descriptor vector.

This will work as long as, going forward, the first vector remains untouched.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download