Closures and C ++ Templates

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?

+3
source share
4 answers

, " ".

, ++ 0x . .

+5

. GOTW # 58 - , . .

++ (14.3.1/2):

   A local type, a type with no linkage, an unnamed
   type or a type compounded from any of these types
   shall not be used as a template-argument for a
   template type-parameter.  [Example:
    template <class T>
    class X { /* ... */ };
    void f()
    {
      struct S { /* ... */ };
      X<S> x3;  // error: local type used as
                //  template-argument
      X<S*> x4; // error: pointer to local type
                //  used as template-argument
    }
   --end example]

, , std:: sort, , , gcc .

( ), , . S vector<S> function<..,S>, , .

+5

, , , .

: ... - .

, , , , , .

, , . .

+1

I know the question is a bit outdated, but a simpler solution is to enable the standard C ++ 0x mode in g ++, since it already supports instantiating with locally defined types.

g++ -std=c++0x filename.cpp -o filename
0
source

Source: https://habr.com/ru/post/1718074/


All Articles