dimanche 28 juin 2015

Variadic templates for command line parsing - having compilation errors

I'm trying to parse the command line arguments using variadic templates and tuples. The syntax I'm trying to achieve is

 std::tie(power, nLevels) = ParseCommandLineEx(argc, argv,"Power",3.0,"num levels",4)

That is, I forward main()'s argc & argv arguments, then come a series of argument names alternating with matching typed default arguments. The program should read the arguments (power, nLevels) from the command line, and in case there aren't enough arguments, set the values to the default. Argument names are given for documentation and error messages generation.

The simplified code goes as following (ignoring argument names and errors for now)

 template <typename ARGNAME, typename ARG>
 tuple<ARG> ParseCommandLineEx(int argc,  _TCHAR* argv[], ARGNAME argName, ARG defaultArg)
 {
     if (argc<=0)
         return make_tuple(defaultArg);
    if (argc==1)
         return make_tuple(WideStringToVal<ARG> (argv[0]));

 }

 template <typename ARGNAME, typename ARG, typename ...ARGS>
 auto ParseCommandLineEx(int argc,  _TCHAR* argv[], ARGNAME argName, ARG defaultArg, ARGS... defaultArgs) -> decltype(tuple_cat(make_tuple(defaultArg),      ParseCommandLine<ARGS...>(argc-1,argv+1, defaultArgs...)))
 {
     ARG param = argc>0 ? WideStringToVal<ARG> (argv[0]) : defaultArg;
     return tuple_cat(make_tuple(param), ParseCommandLineEx<ARGS...>(argc-1,argv+1, defaultArgs...));
 }

 template <typename T> 
 T WideStringToVal(TCHAR *str)
 {
     static_assert(false);
 }


 template <> 
 int WideStringToVal(TCHAR *str)
 {
     return _wtoi(str);
 }

 template <> 
 float WideStringToVal(TCHAR *str)
 {
     return float(_wtof(str));
 }

 int _tmain(int argc, _TCHAR* argv[])
 {
   auto params = ParseCommandLineEx(argc-1, argv+1, "v1",-1.0f,"v2",-1,"v3",-1);
   return 0;
 }

But this does not compile, VC++ Nov2012 CTP compiler fails due to "expects 4 arguments - 8 provided" on the line calling ParseCommandLineEx from _tmain. Can anyone spot the problem?

Aucun commentaire:

Enregistrer un commentaire