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: ");
}
不需要对字符串返回函数进行模板特化,完全匹配的重载函数比函数模板具有更高的优先级。
关于c++ - 如何使此函数使用 getline 读取字符串并使其与 int 的行为相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186453/