如何从头文件向现有结构添加运算符定义?

Nav*_*ngh 5 c++ operator-overloading hashmap visual-c++

我正在SNMP AgentWindows中进行开发。在头文件中,snmp.h有一个struct定义OID值的标识符,其定义如下:

typedef struct {
  UINT   idLength;
  UINT * ids;
} AsnObjectIdentifier; 
Run Code Online (Sandbox Code Playgroud)

我想将其AsnObjectIdentifier用作a的键,unordered_mapstruct定义不会使==运算符重载,这使我想到了是否可以在已定义的运算符中添加运算符重载,struct还是我需要自定义struct包装AsnObjectIdentifier变量。

Pub*_*bby 5

是的,您可以在类之外定义运算符:

bool operator==(AsnObjectIdentifier const& lhs, AsnObjectIdentifier const& rhs)
{
    return /* whatever */;
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以定义自定义相等函数对象并将其传递给unordered_map的第四个模板参数。

  • 继承不应该用于此类事情。那个评论是错误的。 (3认同)

Bia*_*sta 4

您可以简单地在您的中使用自定义函子unordered_map

的确,unordered_map为此目的提供了自定义模板参数。

注意:您还需要提供一个函子来计算哈希值unordered_map

template<
    class Key,
    class T,
    class Hash = std::hash<Key>,   // <----- You need hash for Key
    class KeyEqual = std::equal_to<Key>, // <---- Equal Functor
    // ...
Run Code Online (Sandbox Code Playgroud)

只需根据程序的逻辑定义函子即可。就像是:

struct AsnObjectIdentifierHasher {
  std::size_t operator()(const AsnObjectIdentifier&) const noexcept;
};

struct AsnObjectIdentifierComparator {
  bool operator()(const AsnObjectIdentifier&, 
                  const AsnObjectIdentifier&) const noexcept;
};

template <typename T>
using HashMap = std::unordered_map<AsnObjectIdentifier, 
                                   T, 
                                   AsnObjectIdentifierHasher, 
                                   AsnObjectIdentifierComparator>;
Run Code Online (Sandbox Code Playgroud)

我强烈反对使用自由函数来实现算术和逻辑运算符(特别是当 STL 接口通过模板参数提供自定义时)。函子(函数对象)提供更好的隔离代码并避免范围问题(例如,ADL)。