簡體   English   中英

具有可變返回類型的函數

[英]A function with variable return type

我希望能夠使函數GetInput()接受類作為參數,並返回輸入內容。 函數定義如下所示:

GetInput(class type) {
    if (type == string) {
        string stringInput;
        cin >> stringInput;
        return stringInput;
    }
    else if (type == int) {
        int intInput;
        cin >> intInput;
        return intInput;
    }
    else {
        return NULL;
    }
}

我不知道該函數的返回類型寫什么,因為它可以是字符串或整數。 如何使此功能起作用?

您不能將其設為實際參數,但是可以通過創建函數模板 (也稱為模板函數)來執行類似的操作:

template<class T>
T GetInput() {
    T input;
    cin >> input;
    return input;
}

您可以像這樣使用它:

string stringInput = getInput<string>();
int intInput = getInput<int>();

getInput<string>getInput<int>被認為是由編譯器生成的不同函數-因此為什么將其稱為模板。

注意-如果使用多個文件,則整個模板定義必須放在頭文件中,而不是源文件中,因為編譯器需要查看整個模板才能從中生成函數。

正如您所描述的,您無法使其正常工作。

但是,由於調用者需要知道正在讀取的類型,所以簡單的解決方案是使用模板化函數。

#include <iostream>

//   it is inadvisable to employ "using namespace std" here 

template<class T> T GetInput()
{
    T Input;
    std::cin >> Input;
    return Input;
}

並使用

//   preceding code that defines GetInput() visible to compiler here

int main()
{
     int xin = GetInput<int>();
     std::string sin = GetInput<std::string>();
}

模板化函數適用於任何T類型,這些T類型的輸入流(例如std::cin )支持流傳輸,並且可以按值返回。 您可以使用各種技術(特征,部分專業化)來實施約束(例如,如果函數用於功能邏輯不起作用的類型,則產生有意義的編譯錯誤)或為不同類型提供不同的功能。

當然,由於您所做的只是從std::cin讀取,因此您實際上可以直接讀取

#include <iostream>

int main()
{
    int xin;
    std::string sin;

    std::cin >> xin;
    std::cin >> sin;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM