将字符串与数字进行比较,而无需编写太多运算符重载函数

compare string with a number without writing too many operator overloading functions

本文关键字:太多 运算符 函数 重载 数字 字符串 比较      更新时间:2023-10-16

以下代码适用于将字符串与数字进行比较时"=="的情况(感谢πάντα ῥεῖ提供的解决方案)。">"、">="、"!="、"<"、"<="等呢? 是否可以通过编写函数模板来避免为每个运算符编写函数? 典型的函数模板是针对不同类型的相同操作,但我们对同一类型有不同的操作。

#include <unordered_map>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;

bool operator==(const std::string& s, int i) {
int n = atoi(s.c_str());
return (n == i);
}
int main(int argc, char *argv[])
{
string t("1234");
printf("value is %sn", t.c_str());
if (t == atoi(argv[1])) {
printf("yesn");
} else {
printf("non");
}
}

谢谢。

我假设您有兴趣知道如何在不重载所有运算符的情况下提供将自定义类型与 int 相关的运算符。实现此目的的一种方法是提供对要与自定义类型关联的类型的隐式转换(在本例中为 int)。请参阅下面的示例。

#include <iostream>
using namespace std;
class Foo
{
public:
Foo(int val): _val(val)
{}
operator int()
{
return _val;
}
private:
int _val;
};

int main()
{
Foo foo(2);
cout << foo << endl;
cout << (foo == 2) << endl;
cout << (foo > 3) << endl;
}

这将产生:

2
1
0

现在,如果您只对字符串到整数的情况感兴趣,我只是建议使用 Boost lexical_cast,如 http://www.boost.org/doc/libs/1_58_0/doc/html/boost_lexical_cast/examples.html 中的此示例所示:

#include <boost/lexical_cast.hpp>
#include <vector>
int main(int /*argc*/, char * argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
std::vector<short> args;
while (*++argv)
{
try
{
args.push_back(lexical_cast<short>(*argv));
}
catch(const bad_lexical_cast &)
{
args.push_back(0);
}
}
}

或者,如果您使用的是 C++11,只需遵循以下内容:std::lexical_cast - 有这样的事情吗?

">>=!=<<=等呢?是否有可能通过编写函数模板来避免为每个运算符编写函数?

这听起来像是一个XY问题。
重载所有可能的比较运算符std::string是解决此问题的错误方法。

如果要对作为字符串给出的数字应用数值比较操作,只需将字符串转换为数字一次,然后对转换后的值应用比较,而不是用std::string覆盖每个可能的比较操作:

try {
int i = stoi(argv[1]); // <<< convert once!
if (i == 1234) { // Use numeric comparison operators ...
// ... in any way you like:
// if (i <= 1234) {
// if (i >= 1234) {
// if (i < 1234) {
// if (i != 1234) {
// ....
printf("yesn");
} else {
printf("non");
}
}
catch(const std::exception& ex) {
// conversion to number failed
}