智能指针运算符[] "no match" 当类型为已知长度的数组时

Smart pointer operator[] "no match" when type is array with known length

给定以下代码:

typedef std::unique_ptr<uint8_t[SHA256::DIGEST_SIZE]> sha256hash;

std::ostream& operator<<(std::ostream& os, const sha256hash &hash) {
    // Save old formatting
    std::ios oldFormat(nullptr);
    oldFormat.copyfmt(os);

    // Set up formatting
    os << std::setfill('0') << std::setw(2) << std::hex;

    // Do our printing
    for (int i = 0;i < SHA256::DIGEST_SIZE; i++)
      os << hash[i];

    // Restore formatting
    os.copyfmt(oldFormat);
}

我收到以下错误:

In function ‘std::ostream& operator<<(std::ostream&, const sha256hash&)’:
error: no match for ‘operator[]’ (operand types are ‘const sha256hash {aka const std::unique_ptr<unsigned char [32]>}’ and ‘int’)
   os << hash[i];

我认为 typedef 会给我一个智能指针,其中包含指向 uint8_t 数组的指针,因此 operator[] 应该索引到该数组。我对正在发生的事情的最佳猜测是,我不是说我想要 unique_ptr 指向指向 uint8_t 数组的指针。我想我看到了一些解决这个问题的方法,但我不确定哪个是最好的

  1. typedef std::unique_ptr<uint8_t[]> sha256hash; 编译,但我不完全确定我的重载运算符不会尝试将 any unique_ptr 打印到整数数组。
  2. 我为 int 数组创建了一个容器结构,并在其周围放置了一个 unique_ptr。

由于@PeterT 的,我最终选择了第二个选项。自定义删除器似乎离我太远了,这很容易集成到我现有的代码中。这是我的更改:

//! Light wrapper around SHA256 digest
class SHA256Hash {
  //! The actual digest bits.
  uint8_t buff[SHA256::DIGEST_SIZE];
public:
  //! Pointer to a hash.
  typedef std::unique_ptr<SHA256Hash> ptr;

  //! Default constructor
  SHA256Hash() : buff() { }

  //! Operator to offer convenient buffer access
  uint8_t &operator[](const uint8_t i) { return buff[i]; }

  //! Operator to offer convenient buffer access
  const uint8_t &operator[](const uint8_t i) const { return buff[i]; }

  //! Offers access to the underlying digest
  uint8_t *get() { return (uint8_t *) &buff; }
};

// Delegate to the version that prints references
std::ostream &operator<<(std::ostream &os, const SHA256Hash::ptr &hashp) {
  os << *hashp;
  return os;
}

std::ostream &operator<<(std::ostream &os, const SHA256Hash &hash) {
    // Save old formatting
    std::ios oldFormat(nullptr);
    oldFormat.copyfmt(os);

    // Set up formatting
    os << std::setfill('0') << std::setw(2) << std::hex;

    // Do our printing
    for (int i = 0;i < SHA256::DIGEST_SIZE; i++)
      os << (int) hash[i];

    // Restore formatting
    os.copyfmt(oldFormat);

    return os;
}