C++17 has introduced class template argument deduction. While most of the time it's nothing more than a syntactic sugar, there are cases when it really comes to the rescue, especially in the generic code, like in this case.
Another nice application of this feature is a usage of std::array
. Indeed, now it causes much less pain, just compare these two versions:
std::array arr{ 1, 2, 3, 4, 5 }; // with C++17 template argument deduction
std::array<int, 5> arr{ 1, 2, 3, 4, 5 }; // just a normal C++11 std::array
Indeed, once I decide to add one more element, I can just do it without explicitly changing the type to std::array<int, 6>
.
However, the following doesn't compile:
std::array arr{ 1, 2, 3.f, 4, 5 };
It makes sense that the template argument deduction failed, producing an error like the following:
main.cpp:7:26: error: class template argument deduction failed:
std::array arr{2,4.,5}; // will not compile
However, when I tried to give a hint, it didn't fix the problem:
std::array<float> arr{ 1, 2, 3.f, 4, 5 }; // will not compile as well
Now the compiler error message states the following:
main.cpp:7:21: error: wrong number of template arguments (1, should be 2)
std::array<float> arr{2,4.,5};
^
Why is that? Why can't I provide only some of the template arguments for a class, but I can for functions?