coco cheng
coco cheng

Reputation: 21

Functional Object in Polymorphism

I want to implement Functional Object in Polymorphism as follows:

#include <algorithm>
#include <iostream>

using namespace std;
struct Compare {
    virtual bool operator() (int, int) const = 0;
};
struct Less : public Compare {
    bool operator() (int i, int j)
        const {
        return (i < j);
    }
};
struct Greater : public Compare {
    bool operator() (int i, int j)
        const {
        return (i > j);
    }
};
void f(const Compare& c) {
    int arr[10] = { 4,2,6,7,1,3,5,9,8,0 };
    sort(arr, arr + 10, c);
    for (int i = 0; i < 10; ++i)
        cout << arr[i] << " ";
}
int main()
{
    f(Less());
    f(Greater());
}

But it has an error message "no instance of overloaded function "sort" matches the argument list"

I think that the abstract class cannot have an instance. How can I fix it?

Upvotes: 2

Views: 47

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

std::sort takes the comparator parameter by-value; you can't pass an abstract class like Compare to it. You can pass Less or Greater directly to it.

You can make f template,

template <typename C>
void f(const C& c) {
    int arr[10] = { 4,2,6,7,1,3,5,9,8,0 };
    sort(arr, arr + 10, c);
    for (int i = 0; i < 10; ++i)
        cout << arr[i] << " ";
}

then pass Less or Greater to it like:

f(Less());
f(Greater());

LIVE

Upvotes: 3

molbdnilo
molbdnilo

Reputation: 66371

std::sort wants to copy the ordering function.

There is a standard class that "wraps" a reference and makes it copyable; std::ref.

#include <memory>

... and then ...

sort(arr, arr + 10, std::ref(c));

Upvotes: 3

Related Questions