我正在尝试编写一个可以打印堆栈和队列的函数,我的代码如下
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 << '\n';
} else {
auto elem = cont.front();
std::cout << elem << '\n';
}
cont.pop();
std::cout << elem << '\n';
}
}
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++ 是静态类型的并且没有太多的运行时支持。但我想知道这不起作用的具体原因,以及如何处理。
P.S.:判断容器类型的实际含义是:你可以简单地将一个DFS函数变成BFS,传递一个队列容器而不是一个栈。因此,BFS 和 DFS 可以共享大部分代码。
P.P.S:我在 C++ 11 环境中,但也欢迎回答较早或更新的标准。
最佳答案
if
-else
语句的两个分支都必须是可编译的,这不是您的情况。基于部分特化的许多可能的解决方案之一,甚至应该在 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();
}
}
带有 if constexpr
的 C++17 解决方案:
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();
}
}
关于c++ - 使用 std::is_same,为什么我的函数仍然不能用于 2 种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50253286/