Dlaczego opakowanie w strukturę powoduje, że kod przestaje się kompilować?

0

Czy może ktoś mi wyjaśnić, czemu to się kompiluje:

    #include <iostream>
    #include <set>
    using namespace std;
     
    set<int, bool(*)(int, int)>
    	remaining([](int a, int b)->bool
       		{return a < b;});
     
    int main() {}

http://ideone.com/SVQ88V

A to nie:

    #include <iostream>
    #include <set>
    using namespace std;
     
    struct struktura
    {
    	set<int, bool(*)(int, int)>
      		remaining([](int a, int b)->bool
        		{return a < b;});
    };
     
    int main() {}

http://ideone.com/gJv4v3

I pluje dziwacznymi błędami kompilacji, jako są:

prog.cpp:8:15: error: expected identifier before '[' token
     remaining([](int a, int b)->bool
               ^
prog.cpp:8:33: error: creating array of functions
     remaining([](int a, int b)->bool
                                 ^
prog.cpp:9:7: error: expected ')' before '{' token
       {return a < b;});
       ^
prog.cpp:9:22: error: expected unqualified-id before ')' token
       {return a < b;});
                      ^
prog.cpp: In member function 'std::set<int, bool (*)(int, int)> struktura::remaining()':
prog.cpp:9:15: error: 'a' was not declared in this scope
       {return a < b;});
               ^
prog.cpp:9:19: error: 'b' was not declared in this scope
       {return a < b;});
                   ^

Co za idiotyzm, nie tworzę żadnej tablicy funkcji....!!!!

Ten sam set mogę zadeklarować w przestrzeni globalnej i działa (przetestowałem), ale jako pola struktury już nie mogę zadeklarować??

4

Nie możesz tak zainicjalizować pola klasy. To jest sprzeczne z gramatyką języka.

0

Czyli co, mój jedyny wybór jest taki?

    #include <iostream>
    #include <set>
    using namespace std;
     
    struct struktura
    {
    	set<int, bool(*)(int, int)> remaining;
    	struktura() : remaining([](int a, int b)->bool{return a < b;}) {}
    } s;
     
    int main() {
     
    	s.remaining.insert(8);
    	s.remaining.insert(4);
    	for(int i:s.remaining) cout << i << '\n';
    }

Brzydkie jak ***, ale co zrobić...

Chyba że ma ktoś lepsze pomysły?

2
	set<int, bool(*)(int, int)>
  		remaining{[](int a, int b)->bool
    		{return a < b;}};
1

Wersja najprostsza:

struct Foo
{
	set<int, less<>> bar;
	set<int, greater<>> baz;
};

http://melpon.org/wandbox/permlink/dxU6hOadkjTFntsp

Jeśli Twój komparator jest dłuższy, użyj nazwanej funkcji/funktora dla czytelności. Ja widząc Twój przykładowy kod przy code review zastanawiałbym się nad zjebką ;)

struct Foo
{
	struct EvenFirstThenLess
	{
		template<typename T, typename U>
		bool operator()(T&& t, U&& u) const {
			return t % 2 == 0 && u % 2 == 1 ? true : less<>{}(forward<T>(t),forward<U>(u));
		}
	};

	set<int, EvenFirstThenLess> bar;
};

http://melpon.org/wandbox/permlink/4ntoAtZMgpIIld5E

1 użytkowników online, w tym zalogowanych: 0, gości: 1