【问题标题】:Implementing generic stack in c++在 C++ 中实现通用堆栈
【发布时间】:2016-02-23 12:14:21
【问题描述】:

我正在使用 STL 和 boost 库实现通用堆栈数据结构。

#include <iostream>
#include <cstdio>
#include <stack>
#include <boost/any.hpp>
#include <boost/type_index.hpp>

using namespace std;

class Stack{
    private:
        std::stack<boost::any> st;
    public:
        bool empty();
        int size();
        boost::any top();
        void push(boost::any ele);
        void pop();
};

bool Stack::empty(){
    return st.empty();
}

int Stack::size(){
    return st.size();
}

boost::any Stack::top(){
    return st.top();
}

void Stack::push(boost::any e){
    st.push(e);
}

void Stack::pop(){
    st.pop();
}

int main(){
    Stack st;
    int a = 10;
    st.push(a);
    int b = boost::any_cast<int>(st.top());
    float c = 10.0;
    st.push(c);

}

虽然它工作得很好,但我想在从堆栈中检索项目时避免显式类型转换。我希望以某种方式堆栈应该在根据项目的类型自动进行类型转换后返回项目。

我打算用堆栈维护一个哈希图,它可以存储每个元素的类型信息,并且可以用于在返回之前对每个项目进行类型转换,但我无法将其编写为代码。请给我一些可能的方法。

【问题讨论】:

  • 让你的堆栈成为一个模板类,就像其他 stl 一样,你可能会在不需要 boost.any 的情况下解决你的任务。
  • @user3159253:我认为也许 OP 希望能够将不同类型的项目放在同一个堆栈上。

标签: c++ generics boost stl stack


【解决方案1】:

您不能自动转换为正确的类型;那么top() 函数的返回类型将取决于运行时发生的任何事情。那么,在编译时你会给你的top() 函数提供什么返回类型呢?你能做的最好的事情就是

template <typename T>
T top()
{
  return boost::any_cast<T>(stack.top());
}

编辑:至于您的评论——不,您不能使用auto 返回类型来获得您希望的行为,因为编译器会在编译时推断出auto 代表什么类型时间 - 它推断出你返回的内容:boost::any。任何更具体的东西只能在运行时知道。

【讨论】:

  • @sv_jan5 没有。您需要意识到 C++ 不是动态类型语言(auto 不像 C# 中的 dynamic,而是像 C# 中的 var
  • @sehe 谢谢,我将其添加到我的答案中。
  • 技术上,你可以使用auto作为返回类型(它会推导出boost::any
  • @sehe 你说的没错,当然。澄清。
  • 不使用模板也能达到同样的效果吗?
猜你喜欢
  • 2017-07-27
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 2012-05-24
相关资源
最近更新 更多