Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does auto return type deduction force multiple functions to have the same return type?

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?

like image 472
Marc Andreson Avatar asked Oct 29 '15 12:10

Marc Andreson


People also ask

Can the return type of a function be auto?

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

What is c++ type deduction?

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.


1 Answers

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.

like image 181
chris Avatar answered Oct 07 '22 18:10

chris