开发者

c++ typing confusion with operators << and []

开发者 https://www.devze.com 2023-01-09 04:43 出处:网络
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 er

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);
     开发者_C百科   }
};

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.


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)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消