Jes
Jes

Reputation: 2694

Deduction rule for c++ auto argument

For the following function:

auto foo(auto A) {
  int a = 9 + A;
  return A;
}

What are A being deduced? Does it depend on the caller or it can be deduced to integer because of the integer addition? For example a call foo(1.5f) will deduce A to float?

Upvotes: 0

Views: 97

Answers (2)

Jts
Jts

Reputation: 3527

For example a call foo(1.5f) will deduce A to float?

Yes, but the syntax you are using to define your function is a GCC extension.

Consider using:

template<typename T>
auto foo(T A)
{
    int a = 9 + A;
    return A;
}

Or if if you want a lambda function:

auto foo = [](auto A)
{
    int a = 9 + A;
    return A;
}

In both cases, if it's called with an argument of type float, then the return type of foo will be deduced to float. If you want the return type to to be int then you should return a or cast A to int.

When you use auto as the return type of a function, the return type will be deduced to the type of the first return expression, and you must return the same type if there's different return paths. For example:

if (1 == 1)
    return (float)a;
else
    return (int)b; // Error because the return type has already been deduced to float.

Upvotes: 1

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

This is an extension as far as I know. It will deduce the same as a template parameter. Think of this:

template<typename T> // more verbose equivalent of your code
auto foo(T a) {
  int a2 = 9 + a;
  return a;
}

// ...

foo(1.f); // T is float
foo(std::valarray<int>{1, 5, 8}); // T is std::valarray<int>

And the return type will be deduced as the type of the expression used in the return statement.

Upvotes: 0

Related Questions