I have the following code:
class STFDataPoint {
public:
virtual ImagePoint get_patch_top_left() const = 0;
virtual ImagePoint get_patch_bottom_right() const = 0;
virtual std::string get_image_filename() const = 0;
virtual ~STFDataPoint() = 0;
};
inline STFDataPoint::~STFDataPoint() {}
class TrainingDataPoint : public STFDataPoint{
private:
int row;
int col;
std::string class_label;
ImagePoint patch_top_left;
ImagePoint patch_bottom_right;
std::string image_filename;
public:
TrainingDataPoint(int row, int col, std::string class_label,
const ImagePoint & top_left,
const ImagePoint & bottom_right,
std::string image_filename);
std::string get_class_label() const;
inline bool operator==(const TrainingDataPoint& other) const{
return other.class_label == this->class_label;
}
inline bool operator!=(const TrainingDataPoint& other) const{
return !(*this == other);
}
virtual ImagePoint get_patch_top_left() const;
virtual ImagePoint get_patch_bottom_right() const;
virtual std::string get_image_filename() const;
};
And I am trying to run the following:
bool do_something(vector<STFDataPoint>& data_point){
return true;
}
int main(int argc, char* argv[]) {
ImagePoint left = ImagePoint(2,3);
ImagePoint right = ImagePoint(2,3);
TrainingDataPoint a = TrainingDataPoint(1,2,"",left, right, "");
vector<TrainingDataPoint> b;
b.push_back(a);
do_something(b);
}
But get the following error:
invalid initialization of reference of type ‘std::vector<STFDataPoint>&’ from expression of type `std::vector<TrainingDataPoint>`
however if I change the signature of do_something()
to take in a STFDataPoint
(not a vector of them) it runs fine. Can some one please explain why this is and also if there is a work around?
Thanks
Since vector<TrainingDataPoint>
is not a subtype of vector<STFDataPoint>
you cannot do this. Vectors are not covariant in parameter type.
However you can template do_something
to make it work:
template <typename T>
bool do_something(vector<T>& data_point){
//common actions like
ImagePoint leftPatch = data_point[0].get_patch_top_left();
return true;
}