Compilation error with adapter template as instance of operator overload instance

I am trying to use a template adapter for use with an overloaded operator. I get a compilation error (gcc 4.5.2) which seems inconsistent to me. I would like to know why and how to get around this. The following is simplified code illustrating the problem.

// The adapter
template <typename T>
class A {
    T t;
public:
    A(T t_) : t(t_) {}
};

// Utility function to return an adaptor
template <typename T>
A<T> make_A(T t) {
    A<T> a(t);
    return a;
}

// The operator overload on the adapter
template <typename T>
A<T> &operator<<(A<T> &a, int) {
    return a;
}

// Shows use case
int main(int,char**) {
    auto aa = make_A(1);
    aa << 2;        // Compiles

    // Desired use:
    make_A(4) << 5; // Compile Error
}

Error messages:

main_operatorinsert.cpp: In function ‘int main(int, char**)’:
main_operatorinsert.cpp:28:22: error: no match foroperator<<’ in ‘make_A [with T = int](4) << 5
main_operatorinsert.cpp:18:11: note: candidate is: A<T>& operator<<(A<T>&, int) [with T = int]

Why is the string "aa <2;" compile, where the line is "make_A (4) <5;" not? make_A returns the same type as aa. Why does the compiler get a mismatch? How can I get around this?

+3
source share
2 answers

make_A rvalue, operator<< const const lvalue . , make_A(4) << 5;, operator<< -, , lvalue .

+3

(make_A(4)) l.

const . ++ 11 rvalue.

: -const ?

+2

All Articles