c++ - 具有可变返回类型的函数

标签 c++ function 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;
    }
}

我不知道函数的返回类型应该写什么,因为它既可以是string,也可以是int。我怎样才能使这个功能发挥作用?

最佳答案

你不能使它成为实际参数,但你可以通过创建一个函数模板(也称为模板函数)来做类似的事情:

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

你可以这样使用它:

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

getInput<string>getInput<int>被认为是不同的函数,由编译器生成 - 因此这被称为模板。

注意 - 如果您使用多个文件,整个模板定义必须放在头文件而不是源文件中,因为编译器需要查看整个模板才能从中生成函数。

关于c++ - 具有可变返回类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49163560/

相关文章:

c++ - 了解 C++ 内存模型 : Different values on different runs

c++ - WebP 无损格式概述

c++ - 在游戏编程中,全局变量不好吗?

function - 使用 F# 的“选项<unit->unit> 类型和等式”

PHP 7 接口(interface),返回类型提示和 self

c++ - 为什么返回类型引用输出流?

C++ 访问冲突阅读为什么?

javascript - 使用 Greasemonkey 删除 javascript 函数

r - 将函数中的字符传输到r中的函数

objective-c - 定义为返回 id 的 SEL 如何表示返回 double 的方法?