c++ - C++ 中一个模板函数中使用的类的不常见函数

标签 c++ templates

我将在以下代码中传递“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::queuestd::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/

相关文章:

c++ - 参数的编译时处理

c++ - thread_local 对象的销毁

php - 使用正则表达式解析嵌套的 IF 语句

c++ - 运行时vs编译时多态性:更好的可读性vs编译时错误检查,还有什么更重要?

c++ - SFINAE 方法比较

C++ WM_NCCALCSIZE 未被发送

c++ - 如何确保在不满足条件时不运行特定代码

c++ - WINAPI:查看来自其他进程的消息

c++ - 由于库与 EXE 项目中的编译器指令不匹配而导致内存损坏

c++ - 将迭代器传递给函数