具有变量返回类型的函数
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>();
}
模板化函数将适用于输入流(如std::cin
(支持流并且可以按值返回的任何类型T
。 您可以使用各种技术(特征、部分专用化(来强制约束(例如,如果函数用于函数逻辑不起作用的类型,则产生有意义的编译错误(或为不同类型的提供不同的功能。
当然,由于您所做的只是从std::cin
中读取,因此您实际上可以直接阅读
#include <iostream>
int main()
{
int xin;
std::string sin;
std::cin >> xin;
std::cin >> sin;
}
相关文章:
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 在 c++ 中将函数返回类型指定为模板参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 如何避免模板函数返回类型重复?
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- 为什么在某些情况下从函数返回类型中删除 cv 限定符?
- 模板类内模板类的函数返回类型
- 为什么函数返回类型中不允许参数推导?
- 函数返回类型之前的"define"
- C++推断要隐式调用的模板函数返回类型
- 具有不同模板参数的函数返回类型
- 当函数返回类型为父类时,如何返回子类的对象?
- C++:在原型中声明"auto"函数返回类型仍然会导致在扣除错误之前使用"auto&quo
- C++14 'auto'能够获取函数返回类型,我们还需要 std::result_of<> 吗?
- 函数返回类型中的模板类型推断
- 嵌套模板类返回类型在 C++ 中的头文件中函数返回类型的语法
- C++重写 void 函数返回类型会导致生成失败
- 从函数内部推断函数返回类型
- C++嵌套类函数返回类型和命名空间