mercredi 16 février 2022

c++ ctor template / common function (template restrict iterator) can't compile

I'm writing a class, like std::vector can be construct by n value or iterator [first, last), example code like below:

template<typename T>
class Test1{
public:
    Test1(size_t n, const T& v){
        data_ = new T[n];
        for(size_t i = 0; i < n; ++n){
            data_[i] = v;
        }
    }

    template<typename Iterator>
    Test1(Iterator first, Iterator last){
        size_t n = std::distance(first, last);
        data_ = new T[n];
        while(first != last){
            *data_++ = *first++;
        }
    }

    Test1(){
        if(nullptr != data_){
            delete[] data_;
            data_ = nullptr;
        }
    }

    T* data_;
};

usage:

Test1<int> t1(2, 0);

std::vector<int> vec{1, 2, 3};
Test1<int> t2(vec.begin(), vec.end());

but compile error:

...
In instantiation of Test1<T>::Test1(Iterator, Iterator) [with Iterator = int; T = int]
error: invalid type argument of unary
...

so my question is how to realize the both function, why template can't be compile and how to change it(restrict iterator type)?

Aucun commentaire:

Enregistrer un commentaire