1

I have a list container class (not the std::list) that can store any type. I want to store many std::listS in this container with different types(list<int>, list<string> etc.).

Can I use a generic binary predicate when I am sorting them?

Pseudo code:

template <typename T>
bool compare(const T& input1, const T& input2)
{
    return input1>input2;
}

for(auto i = myList.begin(); i!=myList.end(); ++i) //i is an iterator to a std::list
{
    (*i).sort(compare<decltype(*i)::value_type>);
    //when dereferencing i I get a
    //std::list
}

Is this valid (I am not really sure if I can use decltype this way)?

The problem is I can't get even this simple example to compile:

#include <iostream>
#include <list>
using namespace std;

template <typename T>
void display(const T& input)
{
    for(auto i = input.cbegin(); i!=input.cend(); ++i)
        cout << *i << ' ';
    cout << endl;
    return;
}

template <typename R>
class SomeFunc
{
public:
    bool operator ()(const R& in1, const R& in2)
    {
        return in1>in2;
    }
};

template <typename R>
bool someFunc(const R& in1, const R& in2)
{
    return in1<in2;
}


int main()
{
    list<int> myList;
    myList.push_back(5);
    myList.push_back(137);
    myList.push_back(-77);
    display(myList);
    myList.sort(SomeFunc<decltype(myList)::value_type>());
    display(myList);
    myList.sort(someFunc<decltype(myList)::value_type>);
    display(myList);

    cin.ignore();
    return 0;

};

Correction: It does compile here: http://ideone.com/ZMcjSJ Not on my VS2012 though... I'm starting to hate VS. Can anybody clarify a possible reason why it wouldn't compile on VS2012? I obviously have the decltype command in VS2012 but I suppose it doesn't work like a C++ 11 dectype would work? http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx

I tried it in CodeBlocks with gnu gcc set to C++ 11 - works fine.

4

1 回答 1

2

是的,该方法std::list<T>::sort()有一个重载,它需要一个比较函子:

template <typename T>
struct MyComparator
{
    bool operator() const (const T& input1, const T& input2)
    {
        return input1 > input2;
    }
};
...
myList.sort(MyComparator<T>());
于 2013-06-03T16:47:20.400 回答