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

时间:2016-03-16 13:55:54

标签: c++ c++11 inheritance

我正在尝试将std::vector类模板继承到我的membvec类模板中public。我希望将其用作例如。membvec<float> mymemb(10),目的是创建包含membvec元素的mymemb变量10

但我无法弄清楚如何编写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)
    ...
};

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

也许你想要这样的东西:

#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;
}
相关问题