简体   繁体   English

如何强制 C++ 使用编译器库定义的运算符 `<`?

[英]How do I force C++ to use the operator `<` defined by the compiler library?

I'm trying to compare strings, where the strings are composed of numerical values only.我正在尝试比较字符串,其中字符串仅由数值组成。

I defined my own operator < to be我将自己的operator <定义为

bool operator<(const string &s1, const string &s2)
{
    if(s1.size() != s2.size()) return s1.size() < s2.size();
    return s1 < s2; // I don't want this to use mine
}

In the last return statement, I want the < used to be the one defined by the C++ library.在最后一个返回语句中,我希望<曾经是 C++ 库定义的那个。 How can I force the program to do this?如何强制程序执行此操作?

Although I would not recommend overloading operator< for standard library classes, you could achieve what you ask for by calling the standard library implementation explicitly, eg:尽管我不建议为标准库类重载operator< ,但您可以通过显式调用标准库实现来实现您的要求,例如:

bool operator<(const std::string& s1, const std::string& s2)
{
    if (s1.size() != s2.size()) {
        return s1.size() < s2.size();
    }
    return std::operator<(s1, s2);
}

UPDATE : As pointed out in the comments, std::operator<(s1, s2) would not work in C++20.更新:正如评论中指出的那样, std::operator<(s1, s2)在 C++20 中不起作用。 I guess using std::less()(s1, s2) would do the trick then, but the way it looks, and the reason why it works (different namespaces), both suggest that this is not the way to go, and creating a custom class is a better solution for your problem.我想使用std::less()(s1, s2)可以解决问题,但是它的外观以及它工作的原因(不同的命名空间)都表明这不是 go 的方式,并创建定制 class 是解决您问题的更好方法。

Others already answered the question directly.其他人已经直接回答了这个问题。 I rather suggest you to not do it;).我宁愿建议你不要这样做;)。 As mentioned in a comment: Better don't write an operator< for std::string .如评论中所述:最好不要为std::string编写operator< Its not your type.它不是你的类型。

You have different options if you want to make:如果你想做,你有不同的选择:

std::string a,b;
bool b = a < b;

use your custom comparison.使用您的自定义比较。 Strings that don't compare like std::string aren't std::string s, so it would be natural to have a wrapper.不像std::string那样比较的字符串不是std::string s,所以有一个包装器是很自然的。 Either make the wrapper own the string, or just let it keep a reference:要么让包装器拥有字符串,要么让它保留一个引用:

struct my_string {
     const std::string& data;
     bool operator<(const my_string& other) {
         return ...;
     }
};

So that you can write:这样你就可以写:

std::string a,b;
bool b = my_string{a} < my_string{b};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM