D
D
Dmitry2017-08-03 20:27:46
C++ / C#
Dmitry, 2017-08-03 20:27:46

What happens to a function when I specify the argument type as auto?

Are you creating multiple functions with different parameters?
How effective or inefficient is it?
Example

#include <iostream>

void print(auto x) {
  std::cout << x << std::endl;
}

int main() {
  print(5);
  print("hello");
  print('c');
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Zhilin, 2017-08-03
@cosmoskey

This function declaration is equivalent to a function template:

template<typename T>
void print(T x) {
    std::cout << x << std::endl;
}

Compiling will create 3 functions print<int>, print<const char*>, print<char>.
By the way, warning of possible future errors: with this use of auto, the print function takes all arguments by value , and in such situations it is often better by reference. From this point of view, one of the following declarations may be more correct:
void print(const auto& x) {
  std::cout << x << std::endl;
}
void print(auto& x) {
  std::cout << x << std::endl;
}

F
First Last, 2017-08-03
@shindakioku

Read
In Explanation You will find the answer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question