Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is auto for function input parameters a replacement for function templates?

In C++20 the auto keyword can be used for function input parameters. Is this a proper replacement for function templates and are there any practical differences to consider when deciding on which approach to take?

template <typename T>
void myFunction(T& arg)
{
    // ...
}

vs.

void myFunction(auto& arg)
{
    // ...
}

Related to and borrowed code from this old question.

like image 399
joaerl Avatar asked Oct 19 '25 12:10

joaerl


1 Answers

For a function with one argument, there is no difference. With multiple arguments, auto is considered independently for each of them, i.e.

template <typename T>
void myBinaryFunction(T& arg1, T& arg2);

has no simple equivalent with auto, because arg1 and arg2 must deduce to the same type.

Similarly, non-type template parameters can't be auto

template <template <typename...> class Container, size_t N>
void convert(const std::array<int, N> & src, Container<int> & dest);

Nor can type parameters that are not present in the parameters

template <typename T>
T getById(int id);
like image 64
Caleth Avatar answered Oct 21 '25 04:10

Caleth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!