Home > Backend Development > C++ > body text

Why does std::is_same fail when trying to process different container types in a function?

Mary-Kate Olsen
Release: 2024-11-01 14:09:02
Original
188 people have browsed it

Why does std::is_same fail when trying to process different container types in a function?

Using std::is_same: Why the Function Fails to Process Different Container Types

In an attempt to create a versatile function capable of printing both stacks and queues, a developer encounters a compilation error. Despite utilizing std::is_same to discern the container's type, the function remains non-functional.

The error originates from the fact that both branches of the if-else statement must compile successfully, which is violated in this instance. To address this issue, a modification is implemented using partial specialization and element_accessor template struct:

<code class="cpp">template <typename Cont>
struct element_accessor;

template <typename T>
struct element_accessor<std::stack<T>> {
   const T&amp; operator()(const std::stack<T>&amp; s) const { return s.top(); }
};

template <typename T>
struct element_accessor<std::queue<T>> {
   const T&amp; operator()(const std::queue<T>&amp; q) const { return q.front(); }
};

template<typename Cont>
void print_container(Cont&amp; cont){
   while(!cont.empty()){
      auto elem = element_accessor<Cont>{}(cont);
      std::cout << elem << '\n';
      cont.pop();
   }
}
Copy after login

Alternatively, for C 17 and higher, the error can be circumvented using if constexpr rather than partial specialization:

<code class="cpp">template<template<class> typename Cont, typename T>
void print_container(Cont<T>&amp; cont){
   while(!cont.empty()){
      if constexpr (std::is_same_v<Cont<T>, std::stack<T>>) 
         std::cout << cont.top() << '\n';
      else if constexpr (std::is_same_v<Cont<T>, std::queue<T>>) 
         std::cout << cont.front() << '\n';
      cont.pop();
   }
}</code>
Copy after login

The above is the detailed content of Why does std::is_same fail when trying to process different container types in a function?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!