I wrote my generic class "MyVector" based on std::valarray
//myvector.h
#ifndef MYVECTOR_H
#define MYVECTOR_H
#include <valarray>
template <typename T>
class MyVector
{
public:
MyVector(int size){larr.resize(size);}
MyVector<T>& operator=(const MyVector<T>& other)
{
this->larr=other.larr;
return *this;
}
MyVector<T> operator+ ( const MyVector<T>& rhs); //body in .cpp file
template <typename U>
MyVector<T> operator+ (const U& val); //body in .cpp file
protected:
std::valarray larr;
}
#endif
//myvector.cpp
/*****other code*****/
template <typename T>
MyVector<T> MyVector<T>::operator+ ( const MyVector<T>& rhs)
{
MyVector<T> lv; lv.larr = this->larr + rhs.larr;
return lv;
}
template <typename T>
template <typename U>
MyVector<T> MyVector<T>::operator+ (const U& val)
{
MyVector<T> lv; lv.larr = this->larr + static_cast<T> (val);
return lv;
}
/*****other code*****/
Then I try to write a derived class DataVector, with all the functions of MyVector, especially, all my overloaded operators.
#ifndef DATAVECTOR_H
#define DATAVECTOR_H
#include "myvector.h"
class dataVector : public MyVector<int>
{
public:
dataVector& operator=(const dataVector& other)
{
this->larr=other.larr;
return *this;
}
using MyVector<int>::operator=;
using MyVector<int>::operator+;
}
#endif
When I try to compile main.cpp,
//main.cpp
#include "datavector.h"
#include "myvector.h"
dataVector datav1(10);
dataVector datav2(10);
dataVector datav3(10);
//if i write:
datav1=datav1 + 10; //works (gmake and compiler gcc7.5 on ubuntu)
//if i write:
datav3=datav1 + datav2; //does not work (gmake and compiler gcc7.5 on ubuntu)
I obtain this compiler error:
myvector.cpp: In instantiation of ‘MyVector<T> MyVector<T>::operator+(const U&) [with U = dataVector; T = int]’:
myvector.cpp:xxx:yy: error: invalid static_cast from type ‘const dataVector’ to type ‘int’
MyVector<T> lv; lv.larr = this->larr + static_cast<T> (val);
If I use MyVector: MyVector3=MyVector1+MyVector2 works well.
Can anyone help me? I know this code isn't well writed, but I'm still learning. thank you.