我现在正在努力实现一个标准,并且有一个模板类 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
,编译器将引发无法转换类型的错误 void
至 bool*
在代码中 ptr = buffer.data()
.
好吧,对于我当前的实现,这是避免使用 std::vector
的最后一个选项。但 Boost 中的替代方案。我期望的是别名模板的部分特化,但不幸的是,根据 C++ 标准,这是不允许的。因此,我想问一下,有没有其他方法可以解决这样的问题?
最佳答案
您可以对代理类进行部分特化以与别名模板一起使用:
template<typename T, typename Allocator> class
vector_class_impl final
{
public: using type = std::vector<T, Allocator>;
};
template<typename Allocator> class
vector_class_impl<bool, Allocator> final
{
public: using type = something_else<bool, Allocator>;
};
template <typename T, typename Allocator = std::allocator<T>>
using vector_class = typename vector_class_impl<T, Allocator>::type;
关于c++ - 避免别名模板部分特化的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51796860/