Możesz zawsze użyć funkcji, które oferuje ci C++11 i napisać to w tym stylu (to tylko wolna koncepcja, wymagająca poprawek)
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
namespace {
struct argument
{
std::string value;
operator bool() const { return value == "true"; }
operator float() const { return std::stof(value); }
operator int() const { return std::stoi(value); }
operator std::string() const { return value; }
};
template<typename Result, typename... Args, std::size_t... I>
Result call_impl(Result (*function)(Args...), std::vector<std::string> arguments,
std::index_sequence<I...>)
{
return function(argument{arguments[I]}...);
}
}
template<typename Result, typename... Args>
Result call(Result (*function)(Args...), std::vector<std::string> arguments)
{
return call_impl(function, arguments, std::make_index_sequence<sizeof...(Args)>{});
}
template<typename Result, typename... Args>
std::function<void(std::vector<std::string>)> functor(Result (*function)(Args...))
{
return [function](std::vector<std::string> arguments) {
std::cout << call(function, arguments) << std::endl;
};
}
std::vector<std::string> split(const std::string& str, char delim)
{
std::vector<std::string> elements;
std::stringstream stream(str);
std::string element;
while (std::getline(stream, element, delim)) {
elements.push_back(element);
}
return elements;
}
int plus(int x, int y)
{
return x + y;
}
int negate(int x)
{
return -x;
}
int main()
{
using functor_type = std::function<void(std::vector<std::string>)>;
std::map<std::string, functor_type> functions;
functions["add"] = functor(plus);
functions["negate"] = functor(negate);
std::string input;
while (std::getline(std::cin, input)) {
if (input == "quit") {
break;
}
std::vector<std::string> parameters = split(input, ' ');
auto func = functions[parameters[0]];
parameters.erase(parameters.begin());
func(parameters);
}
return 0;
}