【发布时间】:2013-11-01 11:16:45
【问题描述】:
让我们尝试创建一个类似指针的类型匹配 RandomAccessIterator 和NullablePointer 概念。 这里的目标是创建一个自定义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<pointer>(0) - 更新分配器概念中指针的概念要求。
- 不使用带有
std::initializer_list的构造函数(悲伤)
在 C++ 中定义自定义指针有错吗?
这是一个错误吗?
【问题讨论】:
-
制作你的
operator boolexplicit。 chris-sharpe.blogspot.co.uk/2013/07/… -
@BoBTFish 好吧,我现在感觉很愚蠢。非常感谢!
标签: c++ c++11 vector c++-concepts