Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8143251
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T13:04:29+00:00 2026-06-06T13:04:29+00:00

Would love some opinions on this problem I’m trying to workout. I’m trying to

  • 0

Would love some opinions on this problem I’m trying to workout. I’m trying to improve my OO experience and fully leverage C++’s polymorphic capabilities. I’m trying to write some code for a basic command parser. They command structure goes as so:

[command name] [arguments]

The command name will just be limited to a one word string. The arguments can be a 0 to N list of strings.

Each command and list of arguments could be directed to any variety of software objects in my system. So for example I could have an rtp statistics command map to my rtp module, the user statistics to my user module. Something like that.

Right now the entry point for my CLI provides the entire command string as a standard string. And it provides a standard output stream for displaying results to the user.

I really want to avoid using a parser function and then doing an if then else kind of deal. So I was thinking something like this:

  1. I would have a base class called command. Its constructor would take the string command, the stdout, and an interface for the object it needs to interact with.
  2. I would create a command factory that would match the command name to the object that handles it. This would instantiate the right command object for the right command.
  3. Each separate command object would parse the given arguments and make the right choices for this command.

What I’m struggling with is how to give the right module to the right command. Is this where I should use a template argument? So that each command can take any interface and I’ll let the factory decide which module to pass in to the command object?

I’m also open to other opinions as well. I’m just trying to learn and hoping the community can give me some tips :-).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T13:04:30+00:00Added an answer on June 6, 2026 at 1:04 pm

    What you’re looking for is a common pattern in OOP. Design Patterns (the Gang of Four book) referred to this as a Command Pattern.

    There’s generally no need for templates. Everything is parsed and dispatched at runtime, so dynamic polymorphism (virtual functions) is probably a better choice.

    In another answer, Rafael Baptista suggested a basic design. Here is how I would modify his design to be more complete:

    Command objects and CommandDispatcher

    Commands are handled by subclasses of the Command class. Commands are dispatched by a CommandDispatcher object that handles the basic parsing of the command string (basically, splitting at spaces, possibly handling quoted strings, etc.).

    The system registers an instance of Command with the CommandDispatcher, and associates each instance of Command with a command name (std::string). The association is handled by a std::map object, although that could be replaced by a hash table (or similar structure to associate key-value pairs).

    class Command
    {
      public:
        virtual ~Command(void);
        virtual void execute(FILE* in, const std::vector<std::string>& args) = 0;
    };
    
    class CommandDispatcher
    {
      public:
        typedef std::map<std::string, Command*> CommandMap;
    
        void registerCommand(const std::string& commandName, Command* command)
        {
          CommandMap::const_iterator cmdPair = registeredCommands.find(commandName);
          if (cmdPair != registeredCommands.end())
          {
            // handle error: command already registered
          }
          else
          {
            registeredCommands[commandName] = command;
          }
        }
    
        // possibly include isRegistered, unregisterCommand, etc.
    
        void run(FILE* in, const std::string& unparsedCommandLine); // parse arguments, call command
        void dispatch(FILE* in, const std::vector<std::string>& args)
        {
          if (! args.empty())
          {
            CommandMap::const_iterator cmdPair = registeredCommands.find(args[0]);
            if (cmdPair == registeredCommands.end())
            {
              // handle error: command not found
            }
            else
            {
              Command* cmd = cmdPair->second;
              cmd->execute(in, args);
            }
          }
        }
    
    
      private:
        CommandMap registeredCommands;
    };
    

    I’ve left the parsing, and other details out, but this is a pretty common structure for command patterns. Notice how the std::map handles associating the command name with the command object.

    Registering commands

    To make use of this design, you need to register commands in the system. You need to instantiate CommandDispatcher, either using a Singleton pattern, in main, or in another central location.

    Then, you need to register the command objects. There are several ways to do this. The way I prefer, because you have more control, is to have each module (set of related commands) provide its own registration function. For example, if you have a ‘File IO’ module, then you might have a function fileio_register_commands:

    void fileio_register_commands(CommandDispatcher* dispatcher)
    {
      dispatcher->registerCommand( "readfile", new ReadFileCommand );
      dispatcher->registerCommand( "writefile", new WriteFileCommand );
      // etc.
    }
    

    Here ReadFileCommand and WriteFileCommand are subclasses of Command that implement the desired behavior.

    You have to make sure to call fileio_register_commands before the commands become available.

    This approach can be made to work for dynamically loaded libraries (DLLs or shared libraries). Make sure that the function to register commands has a regular pattern, based on the name of the module: XXX_register_commands, where XXX is, for example, the lower cased module name. After you load the shared library or DLL, your code can determine whether such a function exists, and then call it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is something I've pondered/struggled with and would love to hear some opinions on.
I would love to get some tips from other people that have had this
I would love some help on a particular design. This is the code I
I am not sure what's causing this and would love some insight: Started POST
I am currently trying to learn the fundamentals of jquery and would love some
I'd love some other opinions on what's more efficient in this code. Basically in
I have a simple architectural question and would love some advice. I am trying
So I'm very beginner with javascript and would love some help simplifying this code.
I have no experience with regular expressions and would love some help and suggestions
I am in the midst of a short thought experiment and would love some

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.