Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesnt this operator usage in the trailing return type compile?

I was trying to reuse the return type of an operator in my trailing return type of another function, but unfortunately clang did not accept it

struct A {
  int operator[](int);
  auto at(int i) -> decltype((*this)[i]);
};

Clang says that my class does not have a operator[]. Gcc did accept my code. Is my code actually invalid?

like image 901
Johannes Schaub - litb Avatar asked Jan 21 '13 09:01

Johannes Schaub - litb


People also ask

Why use trailing return type c++?

The trailing return type feature removes a C++ limitation where the return type of a function template cannot be generalized if the return type depends on the types of the function arguments.

Can return type be auto?

In C++14, you can just use auto as a return type.

What does Decltype auto do?

decltype(auto) is primarily useful for deducing the return type of forwarding functions and similar wrappers, where you want the type to exactly “track” some expression you're invoking.


2 Answers

I would say that clang is correct, due to 13.3.1.2p3 (1st bullet).

For a unary operator @ with an operand of a type whose cv-unqualified version is T1, and for a binary operator @ with a left operand of a type whose cv-unqualified version is T1 and a right operand of a type whose cv-unqualified version is T2, three sets of candidate functions, designated member candidates, nonmember candidates and built-in candidates, are constructed as follows:

  • If T1 is a complete class type, the set of member candidates is the result of the qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, the set of member candidates is empty.

(emphasis added by @sehe)

like image 149
garfen Avatar answered Oct 03 '22 14:10

garfen


It seems, that it's CLang's bug, because the next code

struct A {
  int operator[](int);
  auto at(int i) -> decltype( this-> operator[]( i ) );
};

compiles by CLang as well - http://liveworkspace.org/code/2Myghk$6

like image 41
borisbn Avatar answered Oct 03 '22 14:10

borisbn