One of the places I hoped I would be able to use the new template argument deduction, was in construction of std::set
's / std::map
s / any other containers with custom comparators - my goal is to create a one-line statement, that will create an efficient set with a lambda comparator.
What I can do since C++11 is:
std::set<int, std::function<bool(int, int)>> s([](int a, int b) {return a > b;});
But since it uses std::function
, it is noticeably slower.
Another option is:
auto mycomp = [](int a, int b) {return a > b; };
std::set<int, decltype(mycomp)> s(mycomp);
It gets the job done, but 1) It requires 2 lines, and creation of the mycomp
variable 2) I need to pass mycomp
's type explicitly.
As I read on reference pages, none of the standard containers has a deduction guide for this kind of situation. Unfortunately, I'm afraid it cannot be even done with the current language standard (C++17), as one can find:
Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place.
What is the reasoning behind this? Why didn't they allow partial argument deduction? I guess there are some problems with it that I overlook, but in my opinion it would be more than helpful.