jsubi
jsubi

Reputation: 9

C++ Avoid if & hardcoded strings

Is there a way to avoid the use of the if and the hardcoded strings in function redirect, the idea is to receive a string and call the apropiate function, maybe with templates/metaprograming..

#include <string>
#include <iostream>

void account()
{
    std::cout << "accout method" << std::endl;
}

void status()
{
    std::cout << "status method" << std::endl;
}

void redirect(std::string method_to_call)
{
    if(method_to_call == "account")
    {
        account();
    }
    else if(method_to_call == "status")
    {
        status();
    }
    else
    {
        std::cout << "method not found!!" << std::endl;
    }
}

int main()
{
    std::string method_name;
    std::cin >> method_name;

    redirect(method_name);

    return 0;
}

Upvotes: 0

Views: 884

Answers (1)

David
David

Reputation: 1530

You can use std::map and std::function to achieve this, although it still required a 'hard coded' string at point of insertion.

void status() 
{
    std::cout << "status" << std::endl;
}

void account()
{
    std::cout << "account" << std::endl;
}

int main()
{
    std::map< std::string, std::function<void()> > functions;

    functions.emplace( "status" , status  );
    functions.emplace( "account", account );

    std::string method_name;
    std::cin >> method_name;

    auto iter( functions.find( method_name ) );
    if( iter != functions.end() )
    {
        iter->second();   
    }
    else
    {
        std::cout << "Method " << method_name << " not found!!" << std::endl;
    } 
}

If you're willing to use macros then you can avoid the extra string like this:

#define ADD_FUNCTION( map, func ) map.emplace( #func, func );

std::map< std::string, std::function< void() > > functions;
ADD_FUNCTION( functions, status  );
ADD_FUNCTION( functions, account );

Upvotes: 3

Related Questions