使用 std::is_same,为什么我的函数仍然不能用于 2 种类型

using std::is_same, why my function still can#39;t work for 2 types(使用 std::is_same,为什么我的函数仍然不能用于 2 种类型)
本文介绍了使用 std::is_same,为什么我的函数仍然不能用于 2 种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试编写一个可以打印堆栈和队列的函数,我的代码如下

I am trying to write a function that can print both stack and queue, my code is as following

template<typename Cont>
void print_container(Cont& cont){
    while(!cont.empty()){
        if(std::is_same<Cont, stack<int>>::value){
            auto elem = cont.top();
            std::cout << elem << '
';
        } else {
            auto elem = cont.front();
            std::cout << elem << '
';
        }
        cont.pop();
        std::cout << elem << '
';
    }
}

int main(int argc, char *argv[])
{
    stack<int> stk;
    stk.push(1);
    stk.push(2);
    stk.push(3);
    queue<int> q;
    q.push(1);
    q.push(2);
    q.push(3);

    std::cout << "print stack" << endl;
    print_container(stk);
    std::cout << "print queue" << endl;
    print_container(q);

    return 0;
}

但是这里不起作用,错误信息是:

demo_typeof.cpp:35:30: error: no member named 'front' in 'std::__1::stack<int, std::__1::deque<int, std::__1::allocator<int> > >'
            auto elem = cont.front();
                        ~~~~ ^
demo_typeof.cpp:52:5: note: in instantiation of function template specialization 'print_container<std::__1::stack<int, std::__1::deque<int, std::__1::allocator<int> > > >' requested here
    print_container(stk);
    ^
demo_typeof.cpp:32:30: error: no member named 'top' in 'std::__1::queue<int, std::__1::deque<int, std::__1::allocator<int> > >'
            auto elem = cont.top();
                        ~~~~ ^
demo_typeof.cpp:54:5: note: in instantiation of function template specialization 'print_container<std::__1::queue<int, std::__1::deque<int, std::__1::allocator<int> > > >' requested here
    print_container(q);
    ^
2 errors generated.

我知道这是有问题的,并且知道 C++ 是静态类型的并且没有太多的运行时支持.但我想知道这不起作用的具体原因,以及如何处理.

I know it's problematic, and know C++ is statically typed and without too much Runtime support. but I am wondering the specific reason why this doesn't work, and how to deal with it.

P.S.:判断容器类型的实际含义是:你可以简单地通过传递队列容器而不是堆栈来将DFS函数更改为BFS.因此,BFS 和 DFS 可以共享大部分代码.

P.S.: The actual meaning of judge the typing of a container is that: You can simply change a DFS function into BFS by passing a queue container instead of a stack. So, BFS and DFS can share most of the code.

P.P.S:我在 C++ 11 环境中,但也欢迎对旧版或更新版标准的回答.

P.P.S: I am in C++ 11 environment, but answers for older or later standard are also welcomed.

推荐答案

if-else 语句的两个分支都必须是可编译的,而在您的情况下则不然.基于部分专业化的许多可能的解决方案之一,即使在 C++98 中也应该工作:

Both branches of if-else 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 << '
';
      cont.pop();
   }
}

<小时>

带有 if constexpr 的 C++17 解决方案:


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() << '
';
      else if constexpr (std::is_same_v<Cont<T>, std::queue<T>>) 
         std::cout << cont.front() << '
';
      cont.pop();
   }
}

这篇关于使用 std::is_same,为什么我的函数仍然不能用于 2 种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)