Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::sort using inherited functor

I would like to use different strategies to sort a vector. But I can't figure out how to pass a child functor and use it in std::sort later on. Whenever I use abstract class for sorting strategy I end up with cannot allocate an object of abstract type error. Is there a way to use inherited functors as std::sort arguments? Thanks!

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


class BaseSort{
public:
    virtual ~BaseSort() {};
    virtual bool operator()(const int& a, const int& b) = 0;
};

class Asc : public BaseSort{
public:
    bool operator()(const int& a, const int& b){
        return a < b;
    }
};

class Desc : public BaseSort{
public:
    bool operator()(const int& a, const int& b){
        return a > b;
    }
};

void print(const vector<int>& values) {
    for (unsigned i = 0; i < values.size(); ++i) {
        cout << values[i] << ' ';
    }
    cout << endl;
}

int main() {
    vector<int> values = {2,1,3};
    sort(values.begin(), values.end(), Asc()); // {1,2,3}
    print(values);
    sort(values.begin(), values.end(), Desc()); // {3,2,1}
    print(values);
    Asc* asc = new Asc();
    sort(values.begin(), values.end(), *asc); // {1,2,3}
    print(values);
    BaseSort* sortStrategy = new Desc();
    sort(values.begin(), values.end(), *sortStrategy); //cannot allocate an object of abstract type ‘BaseSort’
    print(values);
    return 0;
}
like image 314
Boris Mikhaylov Avatar asked Mar 25 '13 00:03

Boris Mikhaylov


1 Answers

You have to use std::ref(), otherwise the argument will be passed by value (causing an attempt to copy-construct an object of type BaseSort, which is illegal since BaseSort is abstract - and even if it were not, you would get slicing):

sort(values.begin(), values.end(), std::ref(*sortStrategy));
//                                 ^^^^^^^^
like image 127
Andy Prowl Avatar answered Oct 08 '22 22:10

Andy Prowl