加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 仅使用静态多态性的异构容器

发布时间:2020-12-16 03:45:56 所属栏目:百科 来源:网络整理
导读:我的目标是实现一个容器(这里是一组堆栈,每种类型一个),同时接受许多不同类型的对象.在运行时,使用void指针(或所有存储类型的公共基类)和运行时类型识别(RTTI),这将是微不足道的.由于容器将要保存的所有类型在编译时都是已知的,因此可能(或可能不)使用模板来
我的目标是实现一个容器(这里是一组堆栈,每种类型一个),同时接受许多不同类型的对象.在运行时,使用void指针(或所有存储类型的公共基类)和运行时类型识别(RTTI),这将是微不足道的.由于容器将要保存的所有类型在编译时都是已知的,因此可能(或可能不)使用模板来创建这样的类.我知道boost :: variant已经提供了类似的功能,但它要求存储的类型作为模板参数列出,如boost :: variant< int,std :: string> v ;.

我真正想要的是一个类,每次创建相当于push()的新模板特化时,它就会透明地向自己添加匹配(内部)数据结构.该类的用法如下所示:

int main()
{
    MultiTypeStack foo;
    //add a double to the container (in this case,a stack). The class would
    //..create a matching std::stack<double>,and push the value to the top.
    foo.push<double>(0.1);
    //add an int to the container. In this case,the argument type is deduced.
    //..The class would create a std::stack<int>,and push the value to the top.
    foo.push(123);
    //push a second double to the internal std::stack<double>.
    foo.push<double>(3.14159);
    std::cout << "int: " << foo.top<int>() << "n";      //"int: 123"
    std::cout << "double: " << foo.top<double>() << "n";//"double: 3.14159"
    return 0;
}

以天真的实现为例:

template<typename T> struct TypeIndex;
template<> struct TypeIndex<int>{enum{i = 0};};
template<> struct TypeIndex<double>{enum{i = 1};};

class MultiTypeStack
{
public:
    template<typename T>
    void push(const T &val){std::get<TypeIndex<T>::i>(stacks_).push(val);}

    template<typename T>
    void pop(){std::get<TypeIndex<T>::i>(stacks_).pop();}

    template<typename T>
    T top(){return std::get<TypeIndex<T>::i>(stacks_).top();}
private:
    std::tuple<std::stack<int>,std::stack<double>> stacks_;
};

解决方法

创建一个std :: unordered_map< std :: type_index,std :: unique_ptr< unknown>>.您键入的访问代码采用类型并找到适当的条目.然后static_cast将未知类型依赖于保存堆栈的T.

确保unknown是stack_holder< T>的基础,并且该unknown具有虚拟析构函数.

这可能不是你想要的,但C类型系统是纯粹的:后面的表达式不能改变“早期”类型.

如果你链接了类型,你可以构造一个更复杂的类型,但这只是在隐藏它们时列出类型.

如果对象是单例,则使用静态局部变量的一些hackery可以工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读