如何在 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;
}
相关文章:
- 可以从std::string继承以提供类型一致性吗
- "std::shared_from_this"不能由其派生类继承吗?
- 从 std::数组私下继承时无法从 std::initializer_list 构造
- C++ std::vector 中的虚拟析构函数继承
- 当键是虚拟继承中涉及的基类指针时,对 std::unordered_map 项的访问崩溃
- 在继承自 std::variant 的类上使用 std::visit——libstdc++ 与 libc++
- std::exception :使用虚函数和继承与变量
- 如何创建一个继承自 std::vector 的类
- 是否可以通过使用 std::variant 来避免继承
- std::bad_weak_ptr 从基类继承 std::shared_from_this 时
- C++通过继承 std::exception 来创建新的异常
- 为自定义类继承std::vector::迭代器
- 错误:当我继承 std::vector 时,在“开始”之前预期“)”
- 如何在 C++11 的用户自定义类模板中继承 std::vector 模板
- 在继承std::vector的类中使用操作符[]
- c++ -从其他对象继承std::元组,并为其添加虚函数
- 尝试继承std::runtime_error时出现编译错误
- 继承 std::容器,包括其提升序列化
- 继承std::basic_streambuf的问题
- 继承std::string类时跳过添加构造函数