![](/img/trans.png)
[英]C++11 std::vector of template class with argument in constructor
[英]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.