Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
josuttis_nm_c20_the_complete_guide.pdf
Скачиваний:
44
Добавлен:
27.03.2023
Размер:
5.85 Mб
Скачать

32

Chapter 2: Placeholder Types for Function Parameters

The fact that the order of template parameters is not as expected might lead to subtle bugs. Consider the following example:

lang/tmplauto.cpp

#include <vector> #include <ranges>

void addValInto(const auto& val, auto& coll)

{

coll.insert(val);

}

template<typename Coll> // Note: different order of template parameters requires std::ranges::random_access_range<Coll>

void addValInto(const auto& val, Coll& coll)

{

coll.push_back(val);

}

int main()

{

std::vector<int> coll;

} addValInto(42, coll); // ERROR: ambiguous

Due to using auto only for the first parameter in the second declaration of addValInto(), the order of the template parameters differs. Due to http://wg21.link/p2113r0, which was accepted for C++20, this means that overload resolution does not prefer the second declaration over the first one and we get an ambiguity error.1

For this reason, be careful when mixing template and auto parameters. Ideally, make the declarations consistent.

2.4Afternotes

auto for parameters of ordinary functions was first proposed together with the option to use type constraints for them by Ville Voutilainen, Thomas Koppe,¨ Andrew Sutton, Herb Sutter, Gabriel Dos Reis, Bjarne Stroustrup, Jason Merrill, Hubert Tong, Eric Niebler, Casey Carter, Tom Honermann, and Erich Keane in http://wg21.link/p1141r0. The finally accepted wording was formulated by Ville Voutilainen, Thomas Koppe,¨ Andrew Sutton, Herb Sutter, Gabriel Dos Reis, Bjarne Stroustrup, Jason Merrill, Hubert Tong, Eric Niebler, Casey Carter, Tom Honermann, Erich Keane, Walter E. Brown, Michael Spertus, and Richard Smith in http://wg21.link/p1141r2.

1 Not all compilers handle this correctly, yet.