Home > Article > Backend Development > Why does std::is_same fail when trying to process different container types in a function?
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& operator()(const std::stack<T>& s) const { return s.top(); } }; template <typename T> struct element_accessor<std::queue<T>> { const T& operator()(const std::queue<T>& q) const { return q.front(); } }; template<typename Cont> void print_container(Cont& cont){ while(!cont.empty()){ auto elem = element_accessor<Cont>{}(cont); std::cout << elem << '\n'; cont.pop(); } }
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>& 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>
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!