这行代码是错误的,无法编译,但我想知道它是否可以修复。
#include <iostream>
template <typename T>
auto getValue()
{
std::cout << "Enter an integral value: ";
T value{};
std::cin >> value;
// I would do input handing later
return value;
}
int main()
{
auto value1{getValue()};
std::cout << value1 << '\n';
}
请指出是否有办法使其成为可能,或者如果不可能,那么为什么?
谢谢你。
我想从用户那里接收一个整数值,并根据他们输入的值创建一个变量。
例如 如果他们进入 56 然后将创建一个整数变量。 如果他们进入 56.78 那么将创建一个双变量,因为它是横向的。
类型在编译时是固定的,因此您的代码无法工作。如果您确实需要这样做,那么有几种方法。
double
的 JavaScript 方法,双精度数可以保存 53 位整数而不丢失精度。std::variant
选项 2 可能看起来像这样:
#include <variant>
#include <iostream>
#include <string>
#include <optional>
std::optional<int> parseInt(const std::string& str)
{
try
{
size_t pos;
int value = std::stoi(str, &pos);
if (pos == str.size())
{
return value;
}
}
catch (std::exception&)
{
}
return {};
}
std::optional<double> parseDouble(const std::string& str)
{
try
{
size_t pos;
double value = std::stod(str, &pos);
if (pos == str.size())
{
return value;
}
}
catch (std::exception&)
{
}
return {};
}
std::variant<int, double> getValue()
{
while (true)
{
std::cout << "Enter a numerical value: ";
std::string str;
std::getline(std::cin, str);
auto i = parseInt(str);
if (i)
{
return *i;
}
auto d = parseDouble(str);
if (d)
{
return *d;
}
}
}