我希望能够创建一个函数 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/