Collision between return type and return type

I am writing code where the return type of the function is quite complex. I would like to use auto to infer from the return type, but this is clearly not possible in a forward declaration. Therefore, I was hoping to at least duplicate the contents of the return statement and do the following:

 int q = 5; // veeery complicated type /* Declaration - the best we can do */ auto f() -> decltype(q); /* Later, in a different file */ auto f() { return q; } 

This results in the following error in GCC 7,

 error: ambiguating new declaration of 'auto f()' note: old declaration 'int f()' 

Of course I could repeat

 auto f() -> decltype(q) { return q; } 

in the definition (which works), but why do I need it when the return type is already uniquely specified by the return ? How is type f in my definition ultimately more ambiguous than int f() ?

+5
source share
1 answer

The problem is that the final return does not match the purely inferred return type. In [dcl.spec.auto] / 2

[...] If the function declarator includes a return type (8.3.5) that indicates the declared return type of the function

So

 auto f() -> decltype(q); 

really

 int f(); 

which is different from

 auto f() 

There is also [dcl.spec.auto] / 13

Repeated formulations or specializations of a function template or function with a declared return type that uses a placeholder type should also use that placeholder, not a deduced type. [Example:

 auto f(); auto f() { return 42; } // return type is int auto f(); // OK int f(); // error, cannot be overloaded with auto f() decltype(auto) f(); // error, auto and decltype(auto) don't match 

Which is the opposite of what is happening here, but it once again illustrates that it is not allowed

+8
source

Source: https://habr.com/ru/post/1272236/


All Articles