【问题标题】:Concept and GCC implementation of std::vectorstd::vector 的概念和 GCC 实现
【发布时间】:2013-11-01 11:16:45
【问题描述】:

让我们尝试创建一个类似指针的类型匹配 RandomAccessIteratorNullablePointer 概念。 这里的目标是创建一个自定义Allocator 为了将 std::vector 与我们的指针类型一起使用。你可以找到sn-p here

尝试编译此代码时出现问题:

int main()
{
     std::vector<float, allocator<float>> t {0.f, 0.f};
}

我们收到以下错误消息:

/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/stl_vector.h:173:6: error: 
  value of type 'pointer' (aka 'ptr_like<int>') is not contextually convertible
  to 'bool'
    if (__p)

这里我们看到我们的类型必须是 bool 可转换的。做到这点不难 如果人们有我们指针类型的实例,他们很可能会像这样使用它。 因此,让我们这样做并取消对我们的 sn-p 的以下注释:

// In detail::ptr_like we add :
operator bool() const;

我们在 clang 中得到以下错误:

/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/stl_vector.h:168:25: error: 
  conditional expression is ambiguous; 'pointer' (aka 'ptr_like<int>') can be
  converted to 'int' and vice versa
  { return __n != 0 ? _M_impl.allocate(__n) : 0; }

Clang 的错误向我们展示了我们在这里遇到麻烦的确切原因。 现在我发现的唯一可行的解​​决方案如下:

  • 在请求 c++11 时将 0 替换为 c++11 关键字 nullptr
  • 0 替换为指针类型static_cast&lt;pointer&gt;(0)
  • 更新分配器概念中指针的概念要求。
  • 不使用带有std::initializer_list的构造函数(悲伤)

在 C++ 中定义自定义指针有错吗?

这是一个错误吗?

【问题讨论】:

标签: c++ c++11 vector c++-concepts


【解决方案1】:

扩展我的评论。

{ return __n != 0 ? _M_impl.allocate(__n) : 0; }

第一个结果可以转换为boolint。第二个结果可以转换为int。这与将第二个结果转换为pointer 一样好,所以它是模棱两可的。

但我们不希望在此处提供bool 转换,因此我们可以将其设为explicit。正如我所描述的here,它仍然可以在逻辑条件等情况下使用。 在上下文中可转换为 bool 是另一个条件标准放置在满足 NullablePointer 要求的自定义指针类型上(自 2011 年起 - 请参阅 17.6.3.3/3)。

【讨论】:

    【解决方案2】:

    我建议将转换运算符定义为显式。例如

    explicit operator bool() const;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2018-05-31
      • 2021-10-01
      • 2018-12-04
      • 2014-07-15
      • 1970-01-01
      相关资源
      最近更新 更多