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

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

本文关键字:继承 std vector 模板 C++11 用户 自定义 用户自定      更新时间:2023-10-16

我正在尝试将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;
}