Return vector as auto from function

Viewed 1215

Is it possible to return std::vector as auto? For example:

auto retVec() {
  std::vector<int> vec_l;

  l.push_back(1);
  l.push_back(2);

  return vec_l;
}
...
auto ret_vec = retVec();
for (auto& it : ret_vec) {
}

when I write something like this I get an error:

  1. error: use of auto retVec() before deduction of auto ---> auto ret_vec = retVec(**)**;
  2. error: unable to deduce auto&& from ret_vec ---> for (auto it : **ret_vec**) {

How do I actually write this?

UPDATE: I'm sorry. I use this retVec as method in class and it doesn't work. When I use it as function in class - everything work fine. My mistake in formulating the question.

3 Answers

You are compiling for the C++11 standard. You need to compile for at least the C++14 standard as the deduced return type is only available starting with C++14. The reference states:

In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.

You can see this error on Coliru when compiling with -std=c++11, but this works as intended when compiled with -std=c++14.

Note that gcc even outputs a hint at this:

main.cpp:8:13: note: deduced return type only available with -std=c++14 or -std=gnu++14

Deducted return type using auto is indeed a C++14 feature, see Item (3).

This works since C++14 (see here) and not with C++11 (here).

Related