简体   繁体   English

模板函数覆盖std :: vector :: assign

[英]Template function to override std::vector::assign

I am writing a C++ class which contains a member vector . 我正在写一个包含成员vector的C ++类。 I would like to override the vector methods so that MyVector can be used like a std::vector . 我想重写vector方法,以便MyVector可以像std::vector一样使用。 However, the assign method keeps throwing a compile error: 但是, assign方法不断抛出编译错误:

#include <vector>

template<class T>
struct MyVector {
    typedef std::vector<T> vector_type;

    vector_type my_vector;

    template<class It>
    void assign(It first, It last)
    {
        my_vector.assign<It>(first, last);
    }
};

The error: 错误:

myvector.cpp: In member function ‘void MyVector<T>::assign(It, It)’:
myvector.cpp:12:22: error: expected primary-expression before ‘>’ token
my_vector.assign<It>(first, last);

This code compiles without the outer template T . 该代码在没有外部模板T情况下进行编译。 In other words, by changing the vector type to: 换句话说,通过将向量类型更改为:

typedef std::vector<int> vector_type;

will make the compile error go away, but it doesn't serve my needs though. 将使编译错误消失,但是它不能满足我的需求。

The code is compiled on Linux (Ubuntu 18) with gcc version 7.4.0: 该代码在Linux(Ubuntu 18)上以gcc版本7.4.0编译:

gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1) gcc版本7.4.0(Ubuntu 7.4.0-1ubuntu1〜18.04.1)

You need to use the keyword template to tell that assign is a template. 您需要使用关键字template来告诉assign是模板。

my_vector.template assign<It>(first, last);
//        ^^^^^^^^

BTW: The template parameter of std::vector::assign could be deduced automatically, so you don't need to specify the template argument explicitly in fact. 顺便说一句: std::vector::assign的模板参数可以自动推断,因此实际上您不需要显式指定模板参数。 So just 所以就

my_vector.assign(first, last);

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

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