我将在以下代码中传递“stack”和“queue”作为模板类型。
知道.front()和.top()不是“queue”和“stack”之间的公共(public)函数,所以我使用“if”来检查。
但是还是无法编译。 (错误 C2039:“top”不是 std::queue<_Ty> 的成员)
有什么办法可以解决这个问题吗?
template<typename T>
void push_pop(string *str, T *containers){
string s = typeid(containers).name();
if(s[11]=='q'){
str->push_back(containers->front()); containers->pop();
}else{
str->push_back(containers->top()); containers->pop();
}
}
我知道我可以使用函数重载,但我想使用模板来解决这个问题。
感谢您的回答!
最佳答案
问题在于编译器必须编译检查的两个分支,并且无法编译队列的 container.top()
和 container.front()
对于堆栈。
您必须为 std::queue
和 std::stack
实现单独的函数模板:
template<typename V, typename C>
void push_pop(std::string &str, std::stack<V, C> &container) {
str.push_back(container.top());
container.pop();
}
template<typename V, typename C>
void push_pop(std::string &str, std::queue<V, C> &container) {
str.push_back(container.front());
container.pop();
}
可以(并且我建议这样做)仅对相关部分执行此操作:
template<typename V, typename C>
V const &first_element(std::stack<V, C> const &container) {
return container.top();
}
template<typename V, typename C>
V const &first_element(std::queue<V, C> const &container) {
return container.front();
}
template<typename T>
void push_pop(std::string &str, T &container) {
str.push_back(first_element(container));
container.pop();
}
关于c++ - C++ 中一个模板函数中使用的类的不常见函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27938827/