Home > Backend Development > C++ > Why is `printme({\'a\', \'b\', \'c\'});` Illegal in C Template Type Deduction?

Why is `printme({\'a\', \'b\', \'c\'});` Illegal in C Template Type Deduction?

Patricia Arquette
Release: 2024-12-02 20:24:14
Original
492 people have browsed it

Why is `printme({'a', 'b', 'c'});` Illegal in C   Template Type Deduction?

Type Deduction in Functions with Initializer Lists

Consider the function template:

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

This function expects one parameter of a type with a begin() and end() function.

Question:

Why is the following call illegal?

printme({'a', 'b', 'c'});
Copy after login

Answer:

The call printme({'a', 'b', 'c'}) is illegal because the template argument T cannot be inferred. Without specifying the template argument explicitly, the compiler cannot determine the type of the parameter, as it could be any type with a begin() and end() function. This issue does not arise in the following cases:

  • Explicit template argument specification: printme>({'a', 'b', 'c'})
  • Parameter types with type deduction: printme(std::vector({'a', 'b', 'c'}))
  • Using auto to deduce the type: const auto il = {'a', 'b', 'c'}; printme(il);
  • Explicitly specifying the template argument: printme>({'a', 'b', 'c'})
  • The exception to this is the deduction of auto as std::initializer_list, which differs from the template argument deduction. This behavior is explicitly specified in the C 11 standard (§ 14.8.2.5/5), which states that the template argument for a function parameter that is an initializer list but not of type std::initializer_list is not deduced. However, § 7.1.6.4/6 of the standard provides explicit support for auto to deduce std::initializer_list<>.

    The above is the detailed content of Why is `printme({\'a\', \'b\', \'c\'});` Illegal in C Template Type Deduction?. 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