【发布时间】:2018-10-19 13:36:06
【问题描述】:
我正在尝试编写一个可以打印堆栈和队列的函数,我的代码如下
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语句的两个分支,但其中一个总是会失败。 -
因为
if-else语句的两个分支都必须是可编译的,而您的情况并非如此。您可以使用 C++17 中的if constexpr,或者基于 SFINAE、部分专业化等的一些解决方案。