traveh
traveh

Reputation: 2884

Are there cases in C++ where the auto keyword can't be replaced by an explicit type?

I came across the following code:

auto x = new int[10][10];

Which compiles and runs correctly but I can't figure out what would be the type for defining x separately from the assignment.

When debugging the type shown is int(*)[10] for x but int (*) x[10]; (or any other combination I tried) is illegal.

So are there cases where auto can't be replaced by an explicit type...? (and is this such a case?)

Upvotes: 0

Views: 225

Answers (3)

alfC
alfC

Reputation: 16272

That is not a case in which you have to necessarily use auto.

But answering the question in the title, I can think of 3 cases where you need auto.

  1. As @IgorTandetnik said in a comment, lambas. auto f = [](){...};.

  2. returning of a local class, which has its uses.

auto f() {  // auto needed here
  struct A{
    double x;
    double y;
  };

  return A{...};
};
...
auto result = f();  // auto needed here
  1. Unnamed class (or enums)
struct {
...
} pi;

auto pi2 = pi;

Case 2 is sometimes used to define an ad-hoc type.

For example, what type should a minmax(std::vector<double> const&) return?

You could return some standard type std::pair<double, double>, but why would .first and .second indicate the two results?

With this instead, the labels are more clear and you don't have class dissociated with the specific purpose.

auto minmax(std::vector<double>& v) {
   struct result_t{
      double min;
      double max;
   }
   ...
   return result_t{m, M};
}
...

auto result = minmax(v);
... use result.min and result.max ...

Upvotes: 1

Jarod42
Jarod42

Reputation: 217880

For this kind of types, using typedef might help usage:

template <typename T, std::size_t N>
using CArray = T[N];

and then

CArray<int, 10>* x = new CArray<int, 10>[10];

Else, the syntax is quite "ugly":

int (*x)[10] = new int[10][10];

Upvotes: 0

user12002570
user12002570

Reputation: 1

The type of x is int (*)[10]. There are different ways of figuring this out. The simplest is to just try assigning 5 to x and noticing what the error says:

error: invalid conversion from 'int' to 'int (*)[10]' [-fpermissive]
   13 |     x = 4;
      |         ^
      |         |
      |         int

Or just use static_assert:

static_assert(std::is_same<decltype(x), int(*)[10]>::value);

This means that if you want to explicitly create x(without using auto) then you can do it as:

int (*x)[10] = new int[10][10];

Are there cases in C++ where the auto keyword can't be replaced by an explicit type?

Now coming to the title, one example where auto cannot be directly replaced by explicitly writing a type is when dealing with unscoped unnamed enum as shown below: Demo

enum
{
    a,b,c
}obj;

int main()
{
//--vvvv----------->must use auto or decltype(obj)
    auto  obj2 = obj;
}

Similarly, when dealing with unnamed class. Demo.

Upvotes: 5

Related Questions