We all know that you can simulate closures in C ++ 98 by defining local structures / classes inside a function. But is there a reason why locally defined structures cannot be used to create patterns outside the local area?
For example, it would be very useful to be able to do such things:
void work(std::vector<Foo>& foo_array)
{
struct compareFoo
{
bool operator()(const Foo& f1, const Foo& f2) const
{
return f1.bar < f2.bar;
}
};
std::sort(foo_array.begin(), foo_array.end(), compareFoo());
}
This would be especially useful if you knew you wouldn't need to use compareFoo anywhere else in your code. But alas, this does not compile. Is there a reason the compiler cannot create an instance of the std :: sort function using a locally defined structure?
source
share