[英]Class Method Specialization
Currently using g++-11.3.0, C++20.当前使用 g++-11.3.0,C++20。
I'm trying to make this class that accepts two parameters at construction: a void pointer that points to a pre-allocated block of memory, and the size of the memory block.我试图让这个 class 在构造时接受两个参数:一个指向 memory 预分配块的空指针,以及 memory 块的大小。 The class then iterates through the data block with calls to the
next()
method, which returns a reference of the next available slot in the data block, enclosed in the specified type T
. class 然后通过调用
next()
方法遍历数据块,该方法返回数据块中下一个可用槽的引用,包含在指定类型T
中。
class DataArrayIterator
{
private:
void* data;
size_t maxSize;
size_t size;
public:
template<typename T>
T& next<T>()
{
assert(sizeof(T) + size <= maxSize);
size_t offset = size;
size += sizeof(T);
return *((T*)(static_cast<char*>(data) + offset));
}
DataArrayIterator(void* data, size_t maxSize)
: data{data}, maxSize{maxSize}, size{0}
{
}
};
Compiling the code gives me the error non-class, non-variable partial specialization 'next<T>' is not allowed
.编译代码给我错误
non-class, non-variable partial specialization 'next<T>' is not allowed
。 Is there anything I could do to mimic the same functionality as closely as possible?我能做些什么来尽可能地模仿相同的功能吗? Or are there more suitable alternatives?
还是有更合适的选择?
You don't need any partial specialisation in this case, just introduce a function template:在这种情况下您不需要任何部分特化,只需引入一个 function 模板:
template<typename T>
T& next() {
... // implementation goes here
}
And instantiate the function when needed:并在需要时实例化 function:
auto i = 8;
// val is an int reference with value of 8
auto& val = DataArrayIterator{ &i, sizeof(i) }.next<int>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.