I am trying to print a value of an array element as cout << array[0]
, (where the array is some glorified class using operator[]), but the C++ typing system seems incredibly confusing. The GCC error is this:
example.cpp:44:20: error: no match for ‘operator<<’ in ‘std::cout << a_0.fixedarr<T, N>::operator[] [with T = int, long unsigned int N = 5ul, size_t = long unsigned int](0ul)’
(The entire source comes from something more complicated, but I think I've pared it down to a minimal example).
#include <assert.h>
#include <cassert>
#include <climits>
#include <cstdio>
#include <iostream>
using namespace std;
template<typename T>
class fixedarrRef{
T* ref;
int sz;
public:
fixedarrRef(T* t, int psz){ ref = t; sz = psz;}
T val(){ return ref[0]; }
};
template<typename T, size_t N>
class fixedarr{
public:
T arr[N];
fixedarr(){
for(int i=0; i<N; ++i){
arr[i] = 0;
}
}
inline fixedarrRef<T> operator[] (const size_t i) const{
assert ( i < N);
return fixedarrRef<T>((T*)&arr[i], N-i);
}
};
template <typename T>
ostream & operator << (ostream &out, fixedarrRef<T> &v)
{
return (out << v.val());
}
int main() {
fixedarr<int, 5> a_0;
fixedarrRef<int> r = a_0[0];
cout << (a_0[0]) << endl;
// cout << r << endl;
return 0;
}
Note that the commented code at the end works. Thanks in advance.