using std::is_same, why my function still can’t work for 2 types

Both branches of ifelse statement must be compilable, which are not in your case. One of many possible solutions that is based on partial specialization and should work even in C++98:

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();
   }
}

A C++17 solution with if constexpr:

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();
   }
}

Leave a Comment