Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error message with operator syntax, but not with function syntax

Tags:

c++

templates

Why am I getting an error message when calling unary + with operator syntax? If I call it with function syntax, it is OK. Live demo.

template <int size>
struct Buffer { char buf[size]; };

template <class T>
struct Wrapper { void operator+() {} };

Wrapper<Buffer<-5>> a;

void f1() { +a; }               // error: Buffer<-5>::buf has negative size
void f2() { a.operator+(); }    // OK
like image 808
Dr. Gut Avatar asked Jun 10 '20 22:06

Dr. Gut


1 Answers

The unqualified lookup invokes ADL, which needs to know if there are any friend functions defined in the associated classes. Buffer<-5> is one such, so it is instantiated. The fact that it’s syntactically obvious that it declares no friends doesn’t change the fact that the check for same involves completing the class type, which fails.

As an example let's put Buffer into namespace N, and operator+ into Buffer. If a's type is Wrapper<N::Buffer<5>> (5 rarher than -5), operator+ is found by ADL, and the code compiles (live demo):

template <class T>
struct Wrapper {};

namespace N {
    template <int size>
    struct Buffer {
        template <class T> friend void operator+(const Wrapper<T>&) {}
        char buf[size];
    };
}

Wrapper<N::Buffer<5>> a;

void f1() { return +a; }
like image 84
Davis Herring Avatar answered Nov 14 '22 23:11

Davis Herring