Pergunta

I am aware of the process of function overloading in C++ through the use of differing parameters and definitions. However if I have two functions which are identical apart from their parameters is there a way to only have this definition once.

The functions I have used are to check for correct input (i.e. a number not a character is entered). One is for an int and the other a float. Because of this and the fact that I pass the variable by reference the definitions are exactly identical.

The two functions declarations are as follows:

void        Input       (float &Ref);
void        Input       (int &Ref);

And they then share the common definition of:

Function_Header
{
    static int FirstRun = 0;            // declare first run as 0 (false)

    if (FirstRun++)                     // increment first run after checking for true, this causes this to be missed on first run only.
    {                                       //After first run it is required to clear any previous inputs leftover (i.e. if user entered "10V" 
                                            // previously then the "V" would need to be cleared.
        std::cin.clear();               // clear the error flags
        std::cin.ignore(INT_MAX, '\n'); // discard the row
    }

    while (!(std::cin >> Ref))          // collect input and check it is a valid input (i.e. a number)
    {                                   // if incorrect entry clear the input and request re-entry, loop untill correct user entry.
        std::cin.clear();               // clear the error flags
        std::cin.ignore(INT_MAX, '\n'); // discard the row
        std::cout << "Invalid input! Try again:\t\t\t\t\t"; 
    }
}

If there was a way around having to have two identical copies of the same code while it still being used for both parameter types then I could shorten the code of my programme significantly. I'm sure I'm not the only person with this issue but all my searches are returning are explanations of how to overload functions using multiple definitions.

Any help or advice would be much appreciated.

Foi útil?

Solução 2

Templates are useful:

template <typename T>
void Input (T &Ref)
{
   ...
}


std::string s;
int i;
float f;

Input(s);
Input(i);
Input(f);

Outras dicas

The best (and only ?) solution is to use template

template<class T>
void Input(T& ref)
{
..
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top