How to make functions behave differently for different templates in C++?

Advertisements

A part of my C++ homework is to make the FooClass for this main:

int main()
{
    const int max = 10;

    int x[] = {10, 20, 7, 9, 21, 11, 54, 91, 0, 1};
    FooClass<int> xl(x, max);

    int x2[] = {10, 20, 7, 9, 21, 11, 54, 91, 0, 1};
    FooClass<int, std::greater<int> > xg( x2, max);

    xl.sort();
    xg.sort();
    xl.print();
    xg.print();
}

The goal is to make the first sort ascending and the second descending:

0  1  7  9  10  11  20  21  54  91
91  54  21  20  11  10  9  7  1  0

here is my code so far:

template <typename T, typename F=std::greater<T>>
class FooClass
{
private:
    T *mItems;
    int mItemsSize;
    bool mpermission;

public:
    FooClass(T items[], int itemsSize)
    {
        this->mItemsSize = itemsSize;
        this->mItems = items;
    };

    void print() const
    {
        for (int i = 0; i < mItemsSize; ++i)
        {
            std::cout << mItems[i] << "  ";
        }
        std::cout << std::endl;
    }

    void sort()
    {
        std::sort(mItems, mItems + mItemsSize);
    }

};

My code currently prints out:

0  1  7  9  10  11  20  21  54  91
0  1  7  9  10  11  20  21  54  91

And I am struggling to make my sort function behave differently depending on the input template parameters. Is there any way to make this work?

>Solution :

First of all, you are not using F. You need to pass an instance of F to std::sort:

void sort()
{
    std::sort(mItems, mItems + mItemsSize, F{});
}

Secondly: Your default F would make both your instances in your example sort the array in the same way. To get the expected result, you should make the default F use std::less<T> instead.

template <typename T, typename F=std::less<T>>
class FooClass
{
    //...
};

Leave a ReplyCancel reply