I'm having difficulty with one final part of my code. I am trying to use a delegate or function object to define how input arguments (switches) are processed. My code works 4.0 when not encapsulated in a class. Once I try putting the code into a class, I receive the following error:
Error C2440 '<function-style-cast>': cannot convert from 'initializer list' to 'ConsoleSwitch'.
Something is going wrong with how I am setting the values of an array of ConsoleSwitch. When constructing ConsoleSwitch, one of constructor parameters is the function to define how that switch parses its argument, which is what is causing the compile time error. Below is what I think are the relevant snippets of code.
ConsoleArgumentParser class takes console input and parses it into a struct called ConsoleArgs for the rest of the application to use. class ConsoleArgumentParser
{
public:
ConsoleArgumentParser();
ConsoleArgs sortArguments(int argc, char **argv);
private:
... Rest of class declaration goes here ...
};
ConsoleSwitch is a struct that represents an argument (switch) that can be parsed out of the command line. Its constructor takes a function (delegate) that tells the switch how it is supposed to parse the supplied argument.
#include <functional>
struct ConsoleSwitch
{
ConsoleSwitch() { }
ConsoleSwitch(string shortSwitch, string longSwitch, function<void(const char* value, ConsoleArgs&)> parseFunction, int numberOfArgs)
{
this->shortSwitch = shortSwitch;
this->longSwitch = longSwitch;
this->parseFunction = parseFunction;
this->numberOfArgs = numberOfArgs;
}
... Rest of structure here. ...
};
Below is the constructor for ConsoleArgumentParser, where the possible switches are defined by setting each index of the ConsoleSwitches array. This is where the error is thrown on each attempt to construct the consoleSwitch in regards to the function used to parse.
ConsoleArgumentParser::ConsoleArgumentParser()
{
consoleSwitches[0] = ConsoleSwitch("-H", "--HELP", &ConsoleArgumentParser::parseHelp, 0);
... add other possible switches here ...
}
If I remove the code within ConsoleArgumentParser from a class, everything works fine. See below for working initialization code. I've tried several things, but really don't know what is wrong here.
ConsoleSwitch consoleSwitches[]
{
ConsoleSwitch("-H", "--HELP", parseHelp, 0),
ConsoleSwitch("-?", "--?", parseHelp, 0),
ConsoleSwitch("-D", "--DESTINATIONDIRECTORY", parseDestDirectory, 1),
ConsoleSwitch("-Q", "--QUIET", parseQuiet, 0),
ConsoleSwitch("-O", "--OVERWRITE", parseOverwrite, 0),
ConsoleSwitch("-C", "--COMPRESSION", parseCompressionFormat, 1),
ConsoleSwitch("-S", "--SOURCEDIRECTORY", parseSourceDirectory, 1)
};
Any help is appreciated. If we cannot figure it out, I will just leave the ConsoleArgumentParse code wrapped in a namespace and not make it a class and everything will work. Just looking to make it 100%.
-Brett