[英]C++ Template is sending a "false argument" a bad practice?
std::stoi is throwing some errors in specific cases. std::stoi 在特定情况下抛出一些错误。 I don't want to use try/catch block, so I googled a little bit about char convertion and saw that std::from_chars
was doing exactly what I wanted, without those try/catch block.我不想使用 try/catch 块,所以我在 google 上搜索了一些关于 char 转换的信息,发现std::from_chars
正在做我想要的,没有那些 try/catch 块。
Obviously, using std::from_chars
directly works pretty well, but I don't like the syntax.显然,直接使用std::from_chars
效果很好,但我不喜欢这种语法。 So I started writing my own ToInt()
, ToFloat()
, etc. And was like: "ok, that sounds stupid, let's use template".所以我开始编写自己的ToInt()
、 ToFloat()
等。然后就像:“好吧,这听起来很愚蠢,让我们使用模板吧”。
Here I am:我在这里:
#include <string>
#include <charconv>
#include <iostream>
template <typename T>
T ToNumber(const char* str, T varType)
{
if (!str)
return 0;
T var = 0;
std::from_chars(str, str + strlen(str), var);
return var;
}
int main()
{
std::string t = "123.5";
auto a = ToNumber(t.c_str(), (int)0); // a will be an int (123)
float b = ToNumber(t.c_str(), (int)0); // b will store the value as int (123)
auto c = ToNumber(t.c_str(), (float)0); // c will be a float (123.5)
std::cout << a;
return 0;
}
It actually works, that is not the problem.它确实有效,这不是问题。 But I was wondering... Is it a good practice to send a "false argument" ( T varType
) in order to get the cast done and enable auto
?但我想知道......发送“错误参数”( T varType
)以完成转换并启用auto
是一种好习惯吗?
If not, what is the clever way to write such a function?如果不是,写这样一个 function 的巧妙方法是什么?
Thanks in advance提前致谢
You are not checking the return value of std::from_chars
for failure, eg:您没有检查std::from_chars
的返回值是否失败,例如:
auto [p, ec] = std::from_chars(str, str + strlen(str), var);
if (ec != std::errc()) {
...
}
That said, another way to deal with the template argument T
without using a type-casted input parameter is to simply specify the desired type explicitly at the call site instead, eg:也就是说,另一种处理模板参数T
而不使用类型转换输入参数的方法是简单地在调用站点显式指定所需的类型,例如:
template <typename T>
T ToNumber(const char* str)
{
if (!str)
return T{};
T var{};
auto [p, ec] = std::from_chars(str, str + strlen(str), var);
if (ec != std::errc())
return T{};
return var;
}
auto a = ToNumber<int>(t.c_str());
float b = ToNumber<int>(t.c_str());
auto c = ToNumber<float>(t.c_str());
Otherwise, you can use template argument deduction via a reference output parameter (just like std::from_chars()
does), eg:否则,您可以通过引用 output 参数使用模板参数推导(就像std::from_chars()
一样),例如:
template <typename T>
bool ToNumber(const char* str, T &var)
{
if (!str)
return false;
auto [p, ec] = std::from_chars(str, str + strlen(str), var);
return (ec == std::errc());
}
int a;
ToNumber(t.c_str(), a);
int tmp;
ToNumber(t.c_str(), tmp);
float b = tmp;
float c;
ToNumber(t.c_str(), c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.