I have a function that I am trying to convert it to use variadic templates. Unfortunately, the template expansion causes problems when attempting to strongly type the functions during compile time.
Here is the old code:
std::unique_ptr<std::stringstream> Execute(CommandType command, ...) {
auto resp = std::make_unique<std::stringstream>();
va_list vl;
va_start(vl, command);
switch(command) {
case CommandType::Post:
*resp << Post(va_arg(vl, char *), va_arg(vl, char *));
break;
case CommandType::Get:
*resp << Get(va_arg(vl, char *));
break;
case CommandType::Delete:
*resp << Delete(va_arg(vl, char *), va_arg(vl, char *));
break;
}
va_end(vl);
return resp;
}
and the corresponding functions:
bool Post(char *command, char *payload);
char *Get(char *command);
bool Delete(char *command, char *name);
Ideally, I would like to be able to convert this to something along the lines of this:
template< typename... Params>
std::unique_ptr<stringstream> Execute(CommandType command, Params... parameters) {
auto response = std::make_unique<stringstream>();
if(command == CommandType::Get)
response << Get(parameters);
else if(command == CommandType::Post)
response << Post(parameters);
else if(command == CommandType::Delete)
response << Delete(parameters);
else if(command == CommandType::OtherFunc)
response << OtherFunc(parameters);
return response;
};
bool Post(std::string command, std::string payload);
std:string Get(std::string command);
bool Delete(std::string command, std::string name);
int OtherFunc(std::string command, bool enabled, MyClass name);
- OtherFunc added here for more complex type example.
But obviously this doesn't work because the compiler thinks that each command should get the parameters passed into the template when only one based on the CommandType should actually receive the parameters.
Any tricks to rewrite this using templates and maintain strong types, or do I have to leave this using var args and pointers?