Template Type Deduction with initializer_list
Consider the following function:
template<typename T> void printme(T&& t) { for (auto i : t) std::cout << i; }
The above function expects a single parameter with begin() and end() member functions. There are several ways to call this function with different data types. For instance, we can use a std::vector, a std::string, a std::array, or even an initializer list. However, there is one particular case that is illegal:
printme({'a', 'b', 'c'});
This line of code will result in a compile-time error. Why is this the case?
Template Argument Deduction Failure
Type deduction for template arguments can only succeed if the function parameter types match the supplied argument types. In the case of the printme function:
As a result, the compiler is unable to deduce the template argument T in the case of the initializer list argument. Explicitly specifying the template argument will resolve the issue (e.g., printme
Special Case for auto
While the initializer list argument is illegal in the printme function, it is valid to use auto to initialize a variable that holds an initializer list. This is because auto will deduce the type of il as std::initializer_list
The above is the detailed content of Why Does Template Type Deduction Fail with `initializer_list` in This Example?. For more information, please follow other related articles on the PHP Chinese website!