In C++23 we have explicit type convertion auto ( expression )
, and according to cppreference it is already supported by both GCC and Clang.
I have a question where such cast does not occur for some reason. Consider the program:
// OK, x = 0
int x(int(auto(0)));
// OK, f is function template
int f(auto(x));
// error
int y(int(auto(x)));
Here x
declaration is accepted, but very similar y
declaration does not. Online demo: https://godbolt.org/z/f9zor3eTv
GCC:
error: 'auto' parameter not permitted in this context
Clang:
error: 'auto' not allowed in function prototype that is not a function declaration
Is declaration of y
really illegal and compilers are correct in rejecting it?
Had you had a type instead of
auto
, it would read like:However, you cannot put
auto
in place oflong
.[dcl.fct]p22:
[dcl.spec.auto.general]p2
... So the
auto
can only be adecl-specifier
directly in thedecl-specifier-seq
of the type, not nested further. Basically, if you can move theauto
all the way to the left, it will work.So these abbreviated function templates work:
And these ones won't:
The exact same restrictions apply to placeholder types in initializers, like
auto x = ...;
: