Home >Backend Development >C++ >Why Does Template Deduction Fail with Initializer Lists in C ?
Consider the following function:
template<typename T> void printme(T&& t) { for (auto i : t) std::cout << i; }
This function takes a single parameter with a begin()/end() enabled type. However, the following code snippet is considered illegal:
printme({'a', 'b', 'c'});
Despite similar code that utilizes vectors, strings, arrays, and explicit initializer lists working without issue. The question arises, why is this specific snippet illegal?
The key to understanding this issue lies in template argument deduction. In this case, the template argument T cannot be deduced. To rectify this, one must explicitly specify the template argument, as seen below:
printme<vector<char>>({'a', 'b', 'c'}) printme<initializer_list<char>>({'a', 'b', 'c'})
In the aforementioned snippets where the code is legal, the argument possesses a well-defined type, allowing for the template argument T to be inferred seamlessly. The use of auto also enables the function to work, as it infers the type to be std::initializer_list
However, a peculiar behavior arises when comparing the template argument deduction and the auto keyword. While auto infers the type to be std::initializer_list
Nevertheless, the auto keyword specifically supports std::initializer_list<>, allowing the code to function correctly.
The above is the detailed content of Why Does Template Deduction Fail with Initializer Lists in C ?. For more information, please follow other related articles on the PHP Chinese website!