rustyj110 0 Newbie Poster

I am trying to create a text-based menu class to give myself a way to create more dynamic menus in programs. Basically the menu class has a vector of option classes that contain the menu-option's name, function to call etc.

The problem is that I want to be able to associate any function with an option. For example, say that option 1 calls func1( int, string ) and option 2 calls func2( string, ostream&, int ) and so on. Right now I am passing a function pointer but I don't think it is possible to have variable types of arguments with a function pointer.

Here is the code... Any ideas?

/******************************************/
#include "cstdlib"
#include "string"
#include "iostream"

using namespace std;

class Option
{
private:
int option_number; // for display and vector purposes
string name; // title for user to read
void (*func_pointer)( void ); // function to be executed 

public:
Option( int option_number, string name, void (*func_name)() ); // constructor, fills option vars

void callFunction(); // calls function stored in option

// Getters
int getOptionNumber();
string getOptionName();
void (*getFunctionPointer())();
};

class MenuType
{

private:
vector<Option> options;	

public:
MenuType();
void addOption( int option_number, string name, void (*func_name)() );
void displayMenu();

};

/******class Option******/

Option::Option( int option_num, string option_name, void (*func_name)() )
{
option_number = option_num;
name = option_name;
func_pointer = func_name;
}

void Option::callFunction()
{
if ( func_pointer != NULL )
(*func_pointer)();
}

// Getters
int Option::getOptionNumber()
{return option_number;}

string Option::getOptionName()
{return name;}

void (*Option::getFunctionPointer())()
{return func_pointer;}

/******class MenuType******/

MenuType::MenuType()
{}

void MenuType::addOption( int option_number, string name, void (*func_name)() )
{
Option newoption( option_number, name, func_name );
options.push_back( newoption );
}

void MenuType::displayMenu()
{
for ( int i = 0 ; i < options.size() ; i++ )
{
cout<<options[i].getOptionNumber()<<". "<<options[i].getOptionName()<<endl;
}

cout<<"Enter a menu option: ";
int option_choice;
cin>>option_choice;
cin.ignore();

options[option_choice-1].callFunction();
}

/***** Used in a program like this *****/
int main()
{
MenuType first_menu;
first_menu.addOption( 1, "option 1", function ); // but here i would like to be able to put function( arg1, arg2 ). how?
first_menu.addOption( 2, "option 2", function2 ); // but be able to put function2( arg3, arg4, arg5 ) here
first_menu.addOption( 3, "option 3", function3 );
first_menu.displayMenu();
}

Is there a better way to do this? I'm sure there is.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.