【问题标题】:Relational operator overloading for enum class枚举类的关系运算符重载
【发布时间】:2016-06-26 07:41:43
【问题描述】:

我在尝试为枚举类重载小于运算符以用于实验目的时遇到问题,但令人惊讶的是,它仅适用于一元运算符,即 ++。编译器抱怨歧义:

enum class Fruit
{
    apple,
    banana,
    orange,
    pineapple,
    lemon,
};

bool operator<(Fruit l, Fruit r) 
{
    return true;
}

int main()
{
    Fruit f = Fruit::banana;
    Fruit a = Fruit::apple;
    std::cout << (a < f);
}

编译器显然在全局范围内发现了另一个小于运算符,但为什么它不采用重载的运算符,因为它是完全匹配的呢?

【问题讨论】:

  • 我也尝试过 operator
  • 我不明白你的担心。你的operator is actually called?
  • 为我工作。 ideone.com/GO6HWR.
  • gcc 4.9 和 msvc 2015 都有错误:error C2593: 'operator
  • 您是否将程序编译为 C++11 程序?对于gcc,您需要在命令行中使用-std=c++11。我不知道如何在 VS2015 中启用 C++11 功能。

标签: c++ visual-c++ enums overloading


【解决方案1】:

这是一个 Visual C++ 编译器错误,自 2010 年以来一直存在,微软显然不会很快修复它。

Visual Studio bug 529700:

我可以确认这是 Visual C++ 的一个错误。不幸的是 不符合 Visual C++ 当前版本的分类标准 - 但我们会将问题保留在我们的数据库中,我们会查看它 再次在 Visual C++ 未来版本的开发阶段。


一个好的解决方法取决于你想要达到的目标。例如,如果您想将您的 Fruit 放入像 std::mapstd::set 这样的标准容器类中,您可能需要考虑专门化 std::less

namespace std
{
    template<>
    struct less<Fruit>
    {
        bool operator()(Fruit const& lhs, Fruit const& rhs) const
        {
            // your comparison logic
        }
    };
}

std::set<Fruit> s;

或者您为此目的定义一个仿函数类:

struct FruitComparison
{
    bool operator()(Fruit const& lhs, Fruit const& rhs) const
    {
        // your comparison logic
    }
};

std::set<Fruit, FruitComparison> s;

如果您需要对算法进行比较,那么您可能需要使用 lambda:

std::vector<Fruit> v;
std::sort(begin(v), end(v), [](Fruit const& lhs, Fruit const& rhs)
{
    // your comparison logic
});

【讨论】:

    【解决方案2】:

    另一种解决方法(除了Christian Hackl 描述的),对我有用:

    1) 将您的运算符放在命名空间下(在 ma 的情况下 - 与原始枚举相同的命名空间):

    namespace App
    {
        enum class Fruit
        {
            apple,
            banana,
            // ...
        };
    
        bool operator<(Fruit l, Fruit r) 
        {
            return true;
        }
    }
    

    2) 通过全名调用operator&lt;,包括命名空间:

    namespace App
    {
        void foo()
        {
            Fruit f = Fruit::banana;
            Fruit a = Fruit::apple;
    
            std::cout << App::operator<(a, f);
        }
    }
    
    int main()
    {
        App::foo();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-05
      • 2011-02-04
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多