【发布时间】:2018-08-11 05:47:06
【问题描述】:
我现在正致力于实现一个标准,规范中定义了一个模板类vector_class。我只是使用了别名模板
template <class T, class Allocator=std::allocator<T>>
using vector_class = std::vector<T, Allocator>;
在后面的工作中,我有一个函数调用vector_class::data(),它返回一个类型为T*的指针。
除了T 是bool 之外,一切正常。众所周知,std::vector<bool> 是std::vector 类型bool 的一个可能节省空间的特化,它没有实现成员函数data,实际上我的返回类型vector<bool>::data()机器是void。现在问题来了,我们有一些类似的代码:
template <class T>
class A {
public:
vector_class<T> buffer;
T* ptr; // this pointer is defined in the specification thus it is indispensable
A(T* data, size_t size) {
buffer.resize(size);
ptr = buffer.data();
std::copy(data, data + size, ptr);
}
};
如果T 为bool,编译器将在代码ptr = buffer.data() 中引发无法将类型void 转换为bool* 的错误。
嗯,对于我当前的实现,这是避免使用 std::vector 的最后一个选项,但在 Boost.我期望的是类似于别名模板的部分专业化,但不幸的是,根据 C++ 标准,这是不允许的。所以,我想问一下,有没有其他方法可以处理这样的问题?
【问题讨论】: