gpt4 book ai didi

C++ 类型强制推导

转载 作者:行者123 更新时间:2023-11-30 04:04:05 26 4
gpt4 key购买 nike

我正在使用 Colvin-Gibbons 技巧在 C++03 中实现移动语义,我得到了以下内容:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

template <typename T>
class buffer {
struct buffer_ref {
buffer_ref(T* data) : data_(data) {}
T* data_;
};

public:
buffer() : data_(NULL) {}
//explicit buffer(T* data) : data_(data) {}
buffer(size_t size) : data_(new T[size]) {}
buffer(buffer_ref other) : data_(other.data_) { other.data_ = NULL; }
buffer(buffer &other) : data_(other.data_) { other.data_ = NULL; }
~buffer() { delete [] data_; }

operator buffer_ref() { buffer_ref ref(data_); data_ = NULL; return ref; }
operator T*() { return data_; }

private:
T* data_;
};


int main() {
buffer<float> data(buffer<float>(128));
printf("ptr: %p\n", (float*)data);

}

编辑:格式化

我希望能够在方便的时候将我的缓冲区用作指向基类型的指针,因此我向指针类型添加了一个强制转换运算符,它按预期工作。但是,如果我取消注释采用指针的构造函数,那么转换推导会变得困惑并提示不明确的转换(因为它可以转到 buffer->T*->buffer 或 buffer->buffer_ref->buffer)。我希望指针构造函数上的显式修饰符可以解决此问题,但事实并非如此。比我更了解 C++ 转换推导的人可以解释一下编译器的想法吗?

最佳答案

这是 13.3.1.3 [over.match.ctor] 的直接结果:

When objects of class type are direct-initialized (8.5), or copy-initialized from an expression of the same or a derived class type (8.5), overload resolution selects the constructor. For direct-initialization, the candidate functions are all the constructors of the class of the object being initialized. For copy-initialization, the candidate functions are all the converting constructors (12.3.1) of that class. [...]

因为 buffer<float> data(buffer<float>(128));是直接初始化,您已明确请求 explicit考虑构造函数。

如果你写:

buffer<float> data = buffer<float>(128);

那就没有歧义了。

关于C++ 类型强制推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23938354/

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