[英]Subscript operator overload for partial template specialisation
我正在嘗試了解模板和模板專業化。 我正在為數組編寫模板類,使用模板專業化來避免代碼膨脹。 因此,我有一個完全專用的模板MyArray,然后從該模板繼承,例如class MyArray<T*> : private MyArray<void*>
。 我在重載下標運算符時遇到麻煩(一個用於非const引用,一個用於const引用)。 這是一段代碼(遠未完成,但包含了我的問題)。
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
/*** template class MyArray **/
template <class T>
class MyArray {};
/*** Full template specialization for MyArray holding pointers ***/
template <>
class MyArray<void*> {
public:
explicit MyArray(unsigned s = 100) : sz(s) {
data = new void*[s];
}
virtual ~MyArray() { delete[] data; }
/** subscript operator overload for non-const refs **/
void*& operator[](unsigned i) {
return data[i];
}
/** subscript operator overload for const refs **/
const void*& operator[](unsigned i) const {
return data[i]; // line 26
}
unsigned size() const { return sz; }
private:
void** data;
unsigned sz;
};
/** Partial specialization: create the template class by inheriting from the one above **/
template <class T>
class MyArray<T*> : private MyArray<void*> {
public:
explicit MyArray(unsigned s = 100) : MyArray<void*>::MyArray(s) {
data = new T*[s];
}
virtual ~MyArray() { delete[] data; }
/** subscript operator overload for non-const refs **/
T*& operator[](unsigned i) {
return reinterpret_cast<T*&>( // line 47
MyArray<void*>::operator[](i)
);
}
/** subscript operator overload for const refs **/
const T*& operator[](unsigned i) const {
return reinterpret_cast<const T*&>(
MyArray<void*>::operator[](i)
);
}
unsigned size() const { return MyArray<void*>::size(); }
private:
T** data;
};
/** input function for filling MyArray's **/
template <class T>
void InputMyArray(MyArray<T*>& my_array) {
unsigned size = 0;
T tmp;
while (cin >> tmp) {
T* i = new T;
*i = tmp;
my_array[size++] = i;
}
}
/** output function for printing elements of MyArray's **/
template <class T>
void OutputArray(const MyArray<T*>& my_array) {
for (unsigned i = 0; i < my_array.size(); i++) {
cout << *my_array[i] << " ";
}
cout << endl;
}
int main() {
/** Initialize array, fill it, print contents **/
MyArray<int*> p;
InputMyArray(p);
cout << "MyArray of pointer to ints holds int values: " << endl;
OutputArray(p);
return 0;
}
編譯器(clang)抱怨(錯誤)關於第26行
對類型'const void *'的非const左值引用不能綁定到不相關的類型'void *'的值
我想我不希望編譯器將此解釋為非const引用-我想要的是使其成為const。 在這種情況下,如何正確重載該運算符? 對應的代碼段對於沒有專門化的模板類(如MyArray<T>
。
編譯器進一步抱怨(警告)關於reinterpret_cast
,其中顯然包含未定義的行為
從'void *'到'int *&'的reinterpret_cast具有未定義的行為
(第47行)。 reinterpret_casts
本質上是從我的說明中復制粘貼的,因此我認為它們將像這樣使用。 我不知道為什么未引用void*
。 我在這里做錯了什么?
您的模板是void*
的容器,而不是const void*
:
/** subscript operator overload for const refs **/
void* const& operator[](unsigned i) const {
return data[i]; // line 26
}
與T*
相同:
/** subscript operator overload for const refs **/
T* const& operator[](unsigned i) const {
return reinterpret_cast<T*const&>(
MyArray<void*>::operator[](i)
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.