具有变量返回类型的函数

A function with variable return type

本文关键字:函数 返回类型 变量      更新时间:2023-10-16

我希望能够创建一个函数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>();
}

模板化函数将适用于输入流(如std::cin(支持流并且可以按值返回的任何类型T。 您可以使用各种技术(特征、部分专用化(来强制约束(例如,如果函数用于函数逻辑不起作用的类型,则产生有意义的编译错误(或为不同类型的提供不同的功能。

当然,由于您所做的只是从std::cin中读取,因此您实际上可以直接阅读

#include <iostream>
int main()
{
    int xin;
    std::string sin;
    std::cin >> xin;
    std::cin >> sin;
}