2013-10-10 3 views
3

다른 매개 변수와 정의를 사용하여 C++에서 함수 오버로딩 프로세스를 알고 있습니다. 그러나 그들의 매개 변수와 별개로 두 개의 함수가 있다면이 정의를 한 번만 가질 수있는 방법이 있습니다.C++에서 동일한 정의를 사용하여 함수 오버로드

내가 사용한 기능은 올바른 입력 (즉, 문자가 입력되지 않은 숫자)을 확인하는 것입니다. 하나는 int이고 다른 하나는 float입니다. 이 사실과 제가 참조로 변수를 전달한다는 사실은 정의가 정확히 동일합니다.

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

그리고 그들은 다음의 일반적인 정의를 공유 :

선언으로하는 두 가지 기능

다음

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"; 
    } 
} 

방법은 주위에 같은 두 개의 동일한 사본을 할 필요가 있었다면 두 매개 변수 유형에 여전히 사용되는 동안 코드를 상당히 단축 할 수 있습니다. 이 문제가있는 유일한 사람은 아니지만 모든 검색은 여러 정의를 사용하여 함수를 오버로드하는 방법에 대한 설명입니다.

도움이나 조언을 주시면 감사하겠습니다.

+2

사용 기능 템플릿? – taocp

답변

2

템플릿 유용합니다

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


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

Input(s); 
Input(i); 
Input(f); 
+0

당신이 "템플릿 " "템플릿 는" 다른 대답은 을 사용 을 사용했다 는 어떤 차이가 있습니까? – TheWelshBrit

+0

그 맥락에서 전혀 차이가 없습니다. 나는 개인적으로'typename '을 사용하는 것을 선호한다. – bstamour

3

가장 (만?) 솔루션은 템플릿을 사용하는 것입니다

+0

고마워, 전에는 템플릿에 대해 들어 보지 못했지만 cpluspus.com에 대한 설명을 보면 정확히 내가 한 것입니다. – TheWelshBrit

2
template<class T> 
void Input(T& ref) 
{ 
.. 
}