views:

70

answers:

3

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.

A: 

Your [] operator returns an instance of the fixedarrRef class and you are trying to use the operator << on this instance.

Since there is no << operator defined for fixedarrRef you will get and error.

Define this operator and it should work.

Ando
There **is** a `fixedarrRef` operator `<<` defined.
Didier Trosset
I noticed the << operator afterwards :( ( forgot to scroll down the code :( )
Ando
+3  A: 

You should declare both T fixedarrRef::val() and fixedarrRef<T> &v in operator << const.

T val() const { return ref[0]; }

and

template <typename T>
ostream & operator << (ostream &out, const fixedarrRef<T> &v)
Didier Trosset
awesome, what a pain [with c++, not you, thanks for the answer] :)
gatoatigrado
You can read the actual reason **why** you should do this in Naveen's Answer below.
Didier Trosset
+3  A: 

a_0[0] returns a temporary object which can not be bound to a non-const reference, Hence your operator << should take its parameter as a const reference.

Naveen