如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?

How do I make this function read the string with getline and behave the same with an int?

本文关键字:执行 int 字符串 函数 何使此 getline 读取 字符 串并      更新时间:2023-10-16
template<typename T>
T get(const string &prompt)
{
cout<<prompt;
T ret;
cin>>ret;
return ret;
}

我不知道如何使用重载来做到这一点; 基本上,这适用于任何类型的数据,对......

我尝试使用typeid(variable).name();并获得了一个字符串变量的输出,并尝试在 get 函数中创建一个 if。但是它没有奏效。

如您所知,函数不能仅通过返回值类型重载。我注意到您的类型是默认可构造的,因此我将它们用作具有空默认值的函数参数,因此函数可以通过此默认参数类型重载:https://ideone.com/oPSWLC

#include <string>
#include <iostream>
template<typename T>
T get(const std::string &prompt, T ret = T()) {
std::cout << prompt;
std::cin >> ret;
return ret;
}
std::string get(const std::string &prompt) {
std::cout << prompt;
std::string ret;
std::getline(std::cin, ret);
return ret;
}
int main() {
get<int>("int: ");
get<std::string>("string: ");
}

字符串返回函数不需要模板专用化,完全匹配的重载函数比函数模板具有更高的优先级。