繁体   English   中英

如何在C ++ 11的用户定义的类模板中继承std :: vector模板?

[英]How to inherit std::vector template in user-defined class template in C++11?

我想继承std::vector类模板到我membvec类模板作为public 我想将其用作例如 membvec<float> mymemb(10) ,以创建包含10元素的membvec变量mymemb

但是我不知道如何编写public 继承模板声明 我在做什么是以下内容,但都是徒劳的。

template <typename T, template <typename T> class std::vector = std::vector<T>>
//error above: expected '>' before '::' token
class membvec: public std::vector<T>
{
    const membvec<T> operator-() const; // sorry the previous version was a typo 
    //error above: wrong number of template arguments (1, should be 2)
    ...
};

我认为您正在寻找类似以下内容的内容,但请不要这样做。 如果您曾经将类作为其父级std::vector传递,则没有虚拟接口允许您的类提供任何好处。 如果你不需要代替一个std::vector那么就没有必要从它继承。 首选自由函数算法或将std::vector包含为类中的成员。

#include <vector>

template <typename T>
class membvec: public std::vector<T>
{
    // Don't need <T> in class scope, must return by value.
    membvec operator+() const;
};

int main()
{
    membvec<int> foo;
}

也许您想要这样的东西:

#include <vector>                                                   

template <typename T, template <typename T, class Allocator> class Vec = std::vector>
class membvec: public Vec<T, std::allocator<T>>                                                                                             
{
public:
    // This is the signature in your question, but it's questionable.
    const membvec<T, Vec> &operator+(int x) const
    {
        // You obviously want to change this.
        return *this;
    }
};

然后,您可以定期使用它:

int main()
{
    membvec<char> foo;
    foo + 3;
}

暂无
暂无

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

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