繁体   English   中英

使用可变参数模板的成员的类

[英]Class with member that uses variadic template

我试图了解模板的工作方式,并且提出了这个问题。 现在,我完全意识到可以使用多态来解决它,但是我很好奇是否可以仅使用模板来解决它。 情况如下:

假设我有两种队列,它们的定义如下:

#include <queue>
template <typename GenType, typename Comparator>
class Priority
{
public:
    Priority()
    { }
    ~Priority()
    { }
    void insert(GenType const& t)
    { mQueue.push(t); }
private:
    std::priority_queue<GenType, std::vector<GenType>, Comparator> mQueue;
};

template<typename GenType>
class FIFO
{
public:
    FIFO()
    { }
    ~FIFO()
    { }
    void insert(GenType const& t)
    { mList.push_front(t); }
private:
    std::deque<GenType> mList;
};

现在,我有了一个可以使用QueueFIFO (或任何其他类型的队列)的类,如下所示:

// I'm not sure that this is how it should be declared...
template <typename GenType, 
    template<typename, typename...> class List>
class User
{
public:
    User()
    { }
    ~User()
    { }
    void add(GenType const& t)
    { mList.insert(t); }
private:
    // This line gives an error.
    List mList;
};

就目前而言,标记行给出了一个错误,由于我实际上没有将任何模板参数传递给List ,所以我理解了这个错误。 问题是我不知道如何解决此错误。

为了提供一些上下文,此用例是能够使User类采用任何类型的队列,并且可以这样使用:

User<int, FIFO> u1;
// Not sure if it is this way:
User<int, Priority, std::less<int>> u2; 
// Or this way:
User<int, Priority, std::less> u2;

关于如何解决这个问题有什么建议吗?

不要那样做。

相反,让您的User类模板获取将要使用的容器的完整类型 ,并让容器指示其所使用的值的类型:

template <typename Container>
class User
{
public:
    using value_type = typename Container::value_type; // you'll have to add this
                                                       // typedef to your containers

    User() = default;
    ~User() = default;

    void add(value_type const& t)
    {
        mList.insert(t);
    }

private:
    Container mList;
};

这样,作为班级模板的用户,我可以提供正确的东西。 如果我想使用您的优先级队列,可以直接传递我想要的比较器:

User<Priority<int, std::less<>>> u;

或不:

User<FIFO<int>> u2;

或者,也许我写了我自己的甚至不是类模板的容器:

User<SpecialContainer> u3;

您的任一种方式都可以。 泛型是好的。

已经有一个可接受的答案,但是我想显示所需的语法。

private:
    // This line doesn't give an error.
    List<GenType> mList;
};

现在,该行也可以编译:

User<int, FIFO> u1;

由于模板User仅接受两个参数,因此无法编译最后两行。 只需添加第三个参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM