【问题标题】:How could use Template Class for a container of container?如何将模板类用于容器容器?
【发布时间】:2021-04-16 15:07:46
【问题描述】:

我想将我的班级与模板一起使用。 主要:

int main(void)
{
   HexAdapter<vector> foo;
   // maybe?
   // HexAdapter<vector<Cell>> foo;

   return 0;

}

我试过这样的

template <typename T>
class HexAdapter
{
public:
    HexAdapter();

private:
    T<T<Cell>> hexCells;

};

出于这个原因,通常我像这样使用vector&lt;vector&lt;Cell&gt;&gt; hexCells 但我想使用所有带有随机访问迭代器的 STL 容器。

【问题讨论】:

    标签: c++ class oop c++11 templates


    【解决方案1】:

    您可以通过依赖模板模板参数来实现HexAdapter&lt;std::vector&gt;语法,即模板参数,而模板参数又是类模板(或别名模板):

    struct Cell { /* ... */ };
    
    template<template<typename...> class Cont>
    class HexAdapter {
       Cont<Cont<Cell>> hexCells;
       /* ... */
    };
    

    类模板HexAdapter 的模板参数(即Cont 参数的参数)本身必须是一个类模板(例如std::vectorstd::deque):

    auto main() -> int {
       HexAdapter<std::vector> foo;
       HexAdapter<std::deque> bar;
    }
    

    【讨论】:

    • 真正的英雄
    猜你喜欢
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    相关资源
    最近更新 更多