如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
How do I make this function read the string with getline and behave the same with an int?
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: ");
}
字符串返回函数不需要模板专用化,完全匹配的重载函数比函数模板具有更高的优先级。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 为什么在全局范围内使用"extern int a"似乎不行?
- C++,系统无法执行指定的程序
- int(c) 和 c-'0' 之间的区别。C++
- 使用C++中的模板和运算符重载执行矩阵运算
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- 将 int 转换为双精度以执行 std::complex <double>的"*"操作
- std::map<string, int> 在执行 m[0] 时崩溃
- 我可以强制执行标量类型通过 int{} 初始化为零吗?
- 您可以在C 中使用BOOL和INT操作员执行什么操作
- 为什么在执行 int / 无符号 int 除法时使用 'divl'
- 当我在c/cpp中执行int*p=p时会发生什么
- 'x = y = 0'、'x = 0'有什么区别;y = 0;','int x = 0; int y = 0;'关于执行?
- typedef int -> 整数。我可以在 c++ 中执行 cout-> 打印吗?
- 静态int执行多少次
- 将int8_t转换为int,这样我就可以对它执行操作
- 使用 int 和移位执行按位 AND
- 执行 int 3 中断是否会停止 Linux 上的整个过程,还是仅停止当前线程