Consider the below snippet:
struct A { auto foo(), bar(); }; auto A::foo() { return 1; } auto A::bar() { return 'a'; } int main() { }
It compiles fine in Clang++ 3.7.0.
It fails in G++ 5.2.0:
main.cpp: In member function 'auto A::bar()': main.cpp:7:24: error: inconsistent deduction for 'auto': 'int' and then 'char' auto A::bar() { return 'a'; }
Does auto return type deduction force multiple functions, declared in a single statement, to have the same return type?
In C++14, you can just use auto as a return type.
Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.
Based on the following, GCC has the right behaviour in this case, but only by coincidence (see below):
§7.1.6.4 [dcl.spec.auto]/8
If the init-declarator-list contains more than one init-declarator, they shall all form declarations of variables.
Why only by coincidence? The error message is a clue. Changing the functions to deduce the same return type causes GCC to compile the code. While it's correct in giving an error here, albeit a misleading one, it only does so when the deduced type is inconsistent. It should always give an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With