We can use auto with function return type to let compiler to infer type from return value.
For example,
#include <iostream>
#include <typeinfo>
auto add(int a, int b)
{
return a + b;
}
int main(int argc, char const *argv[])
{
std::cout << typeid(add(1, 2)).name() << "\n";
return 0;
}Limitations
- For type deduction for function, function definition has to be available before the use case for the compiler to determine return type. Failing to do so raises compilation error.
- It becomes hard to know the return type of a function from the code.