gpt4 book ai didi

c++ - 比较两个不同的枚举时,是否有避免警告的正确方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:30 24 4
gpt4 key购买 nike

当比较来自不同来源的枚举时,例如以下代码的枚举,GCC 会发出警告。有没有办法在没有 c 风格转换的情况下避免这些警告?

struct Enumerator
{
enum { VALUE = 5 };
};

template<int V>
struct TemplatedEnumerator
{
enum { VALUE = V };
};

if(Enumerator::VALUE == TemplatedEnumerator<5>::VALUE)
{
...
}

并且 GCC 发出以下类型的警告:

GCC: warning: comparison between 'enum ...' and 'enum ...'

最佳答案

我相信您可以提供自己的比较运算符,但您必须先命名枚举:

struct Enumerator
{
enum Values { VALUE = 5 };
};

template<int V>
struct TemplatedEnumerator
{
enum Values { VALUE = V };
};


template <int V>
bool operator==(Enumerator::Values lhs, typename TemplatedEnumerator<V>::Values rhs)
{
return static_cast<int>(lhs) == static_cast<int>(rhs);
}

template <int V>
bool operator==(typename TemplatedEnumerator<V>::Values rhs, Enumerator::Values lhs)
{
return static_cast<int>(lhs) == static_cast<int>(rhs);
}

有趣的是,Visual Studio 实际上并没有对比较两种枚举器类型发出警告,而是对 if 语句中的常量值发出警告 - 就像您这样做一样:

if (true) {...}

关于c++ - 比较两个不同的枚举时,是否有避免警告的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/486555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com