Home >Backend Development >C++ >Why Does Template Deduction Fail with Initializer Lists in C ?

Why Does Template Deduction Fail with Initializer Lists in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 16:39:09643browse

Why Does Template Deduction Fail with Initializer Lists in C  ?

Template Deduction and Initializer Lists

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, the template argument deduction does not. This is because the C 11 standard explicitly states that this is a non-deduced context for a template argument when the function parameter is an initializer list, but the parameter does not have std::initializer_list or a reference to a possibly cv-qualified std::initializer_list type.

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!

Statement:
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