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

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 1:[1]

I would suggest breaking your function down into separate and manageable parts -

function getJson(url) {
  return fetch(url).then(r => r.json())
}

We write fetchGroups (plural) to fetch all groups -

async function fetchGroups(url) {
  const groups = await getJson(url)
  return Promise.all(groups.map(fetchGroup))
}

Where fetchGroup (singular) fetches a single group -

async function fetchGroup({ id, name, locations = [], groups = [] }) {
  return {
    value: id,
    label: name,
    children: [
      ...locations.map(l => ({ value: l.id, label: l.location.name })),
      ...await fetchGroups(`/groups/${id}`)
    ]
  }
}

This arrangement of functions is called mutual recursion and is a perfect fit for creating, traversing, and manipulating recursive structures, such as the tree in your question.

Now we simply call fetchGroups on your initial path -

fetchGroups("/mygroups")
  .then(console.log, console.error)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mulan