Home > Backend Development > C++ > Why Does Template Type Deduction Fail with `initializer_list` in This Example?

Why Does Template Type Deduction Fail with `initializer_list` in This Example?

Susan Sarandon
Release: 2024-11-28 18:47:11
Original
681 people have browsed it

Why Does Template Type Deduction Fail with `initializer_list` in This Example?

Template Type Deduction with initializer_list

Consider the following function:

template<typename T>
void printme(T&& t) {
  for (auto i : t)
    std::cout << i;
}
Copy after login

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'});
Copy after login

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:

  • The std::vector, std::string, and std::array arguments all have well-defined types that correspond to the function's parameter type (e.g., std::vector).
  • The initializer list argument ({'a', 'b', 'c'}) does not have a well-defined type. It is a temporary object that is not associated with a specific type.
  • 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>({'a', 'b', 'c'})).

    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, allowing the compiler to deduce the template argument in printme(il).

    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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template