У меня есть класс контейнера списка (не std::list
), который может хранить любой тип . Я хочу хранить много std::listS
в этом контейнере с различных типов (list<int>
, list<string>
и т. Д.).std :: list.sort(), бинарный предикат?
Можно ли использовать общий двоичный предикат, когда я их сортирую?
Псевдо код:
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
}
Является ли это действительным (я не совсем уверен, если я могу использовать decltype таким образом)?
Проблема в том, что я не могу получить даже этот простой пример компиляции:
#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;
};
Исправление: Он компилировать здесь: http://ideone.com/ZMcjSJ не на моей VS2012 хотя ... Я начинаю ненавидеть VS. Может ли кто-нибудь прояснить возможную причину, почему он не будет компилироваться на VS2012? У меня, очевидно, есть команда decltype в VS2012, но я полагаю, что она не работает, как работает dectype C++ 11? http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx
Я пробовал его в CodeBlocks с gnu gcc, установленным на C++ 11 - отлично работает.