1. C++ / Говнокод #27486

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    // https://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/global/qglobal.h?h=v5.13.1#n1017
    
    #if __cplusplus >= 201703L
    // Use C++17 if statement with initializer. User's code ends up in a else so
    // scoping of different ifs is not broken
    #define Q_FOREACH(variable, container)                                   \
    for (auto _container_ = QtPrivate::qMakeForeachContainer(container);     \
         _container_.i != _container_.e;  ++_container_.i)                   \
        if (variable = *_container_.i; false) {} else
    #else
    // Explanation of the control word:
    //  - it's initialized to 1
    //  - that means both the inner and outer loops start
    //  - if there were no breaks, at the end of the inner loop, it's set to 0, which
    //    causes it to exit (the inner loop is run exactly once)
    //  - at the end of the outer loop, it's inverted, so it becomes 1 again, allowing
    //    the outer loop to continue executing
    //  - if there was a break inside the inner loop, it will exit with control still
    //    set to 1; in that case, the outer loop will invert it to 0 and will exit too
    #define Q_FOREACH(variable, container)                                \
    for (auto _container_ = QtPrivate::qMakeForeachContainer(container); \
         _container_.control && _container_.i != _container_.e;         \
         ++_container_.i, _container_.control ^= 1)                     \
        for (variable = *_container_.i; _container_.control; _container_.control = 0)
    #endif

    А можно ли свой foreach сделать через какую-нибудь шаблонопарашу? Или тут, как обычно, нужна гомоиконность?

    j123123, 28 Июня 2021

    Комментарии (74)
  2. C++ / Говнокод #27483

    +5

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    #include <unistd.h>
    #include <stdio.h>
    #include <limits.h>
    
    template<size_t Size> struct static_string {char data[Size];};
    template<size_t ... Indexes>struct index_sequence {};
    template<size_t Size, size_t ... Indexes>
    constexpr static_string<sizeof ... (Indexes) + 1> make_static_string(const static_string<Size>& str,index_sequence<Indexes ...>) {return {str.data[Indexes] ..., '\0'};}
    constexpr static_string<1> make_static_string() {return {'\0'};}
    template<size_t Size, size_t ... Indexes>
    struct make_index_sequence : make_index_sequence<Size - 1, Size - 1, Indexes ...> {};
    template<size_t Size>
    constexpr static_string<Size> make_static_string(const char (& str)[Size]) {return make_static_string(str, make_index_sequence<Size - 1>{});}
    template<size_t ... Indexes>
    struct make_index_sequence<0, Indexes ...> : index_sequence<Indexes ...> {};
    template<size_t Size, size_t ... Indexes>
    constexpr static_string<sizeof ... (Indexes) + 1> make_static_string(const char (& str)[Size],index_sequence<Indexes ...>) {return {str[Indexes] ..., '\0'};}
    template<size_t Size>
    constexpr size_t static_string_find(const static_string<Size>& str, char ch, size_t from, size_t nth) {return Size < 2 || from >= Size - 1 ? UINT_MAX :str.data[from] != ch ? static_string_find(str, ch, from + 1, nth) :nth > 0 ? static_string_find(str, ch, from + 1, nth - 1) : from;}
    template<size_t Size>
    constexpr size_t static_string_find_0(const static_string<Size>& str, char ch, size_t from, size_t nth) {return Size < 2 || from >= Size - 1 ? 0 : str.data[from] != ch ? static_string_find_0(str, ch, from + 1, nth) :nth > 0 ? static_string_find(str, ch, from + 1, nth - 1) : from;}
    template<size_t Size1, size_t ... Indexes1, size_t Size2, size_t ... Indexes2>
    constexpr static_string<Size1 + Size2 - 1> static_string_concat_2(const static_string<Size1>& str1, index_sequence<Indexes1 ...>,const static_string<Size2>& str2, index_sequence<Indexes2 ...>) {return {str1.data[Indexes1] ..., str2.data[Indexes2] ..., '\0'};}
    template<size_t Size1, size_t Size2>
    constexpr static_string<Size1 + Size2 - 1> static_string_concat_2(const static_string<Size1>& str1, const static_string<Size2>& str2) {return static_string_concat_2(str1, make_index_sequence<Size1 - 1>{},str2, make_index_sequence<Size2 - 1>{});}
    template<size_t Begin, size_t End, size_t ... Indexes>
    struct make_index_subsequence : make_index_subsequence<Begin, End - 1, End - 1, Indexes ...> {};
    template<size_t Pos, size_t ... Indexes>
    struct make_index_subsequence<Pos, Pos, Indexes ...> : index_sequence<Indexes ...> {};
    template<size_t Begin, size_t End, size_t Size>
    constexpr static_string<End - Begin + 1> static_string_substring(const static_string<Size>& str) {return make_static_string(str, make_index_subsequence<Begin, End>{});}
    template<size_t Begin, size_t Size>
    constexpr static_string<Size - Begin> static_string_suffix(const static_string<Size>& str) {return static_string_substring<Begin, Size - 1>(str);}
    #define remove_underscore(arg) ([] () __attribute__((always_inline)) {constexpr auto a = static_string_find(make_static_string(arg),'_',0,0) == UINT_MAX? make_static_string(arg):static_string_concat_2(static_string_concat_2(static_string_substring<0,static_string_find_0(make_static_string(arg),'_',0,0)>(make_static_string(arg)),static_string_suffix<static_string_find_0(make_static_string(arg),'_',0,0)+1>(make_static_string(arg))),make_static_string("\0"));return a;}().data)
    
    int main()
    {
        puts(remove_underscore("_testtest"));
        puts(remove_underscore("test_test"));
        puts(remove_underscore("testtest_"));
    }

    Убогий constexpr в c++11

    mittorn, 25 Июня 2021

    Комментарии (46)
  3. C++ / Говнокод #27474

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    Game::Game()
    {
        run = true;//флаг признак нажатия кнопки выхода F5
        Matrix = new int* [8];//Поле 64 ячейки - значения 0 - для пустой ячейки, для игрока каждая пешка-шашка от 1 до 9, для компьютера значения в матрице от 10 до 18
        for (int i = 0; i < 8; i++)
            Matrix[i] = new int[8];
        //Квадраты координат нужны чтобы программа знала какие ячейки над указателем мыши, 64 квадрата
        QuadCoorXleft = new int* [8];//каждой ячейки матрицы Matrix соответстует квадрат координат для мыши xleft означает левую координату x
        QuadCoorXright = new int* [8];//xright - правая x
        QuadCoorYdown = new int* [8];//верхняя y координата
        QuadCoorYup = new int* [8];//нижняя y координата
        for (int i = 0; i < 8; i++)
        {
            QuadCoorXleft[i] = new int[8];
            QuadCoorXright[i] = new int[8];
            QuadCoorYdown[i] = new int[8];
            QuadCoorYup[i] = new int[8];
        }
        //Координаты пешек для отрисовки
        ChessX = new double[18];//X
        ChessY = new double[18];//Y
        //Выделяемая пешка ее координаты и значения
        ActiveX = -1;//X
        ActiveY = -1;//Y
        Active = -1;//Value
        firstplayer = true;//флаг того что можете игрок 1й ходить
        secondplayer = false;//флаг того что можете игрок 2й ходить
        ai = new bool[18];//ячейки флаги того что пешка на финишной позиции
        chessai tmp;
        for (int i = 0; i < 18; i++)
        {
            ai[i] = false;
            if (i > 8)
            {
                tmp.ai = ai[i];
                tmp.value = i+1;
                Ai.push_back(tmp);//Вектор с флагами финиша каждой пешки для искуственного интеллекта
            }
        }
        aicountfirstrow = 0;//счетчик кол-ва пешек ИИ(искуственного интеллекта) на верхней строчке(0-я)
        aicountsecondrow = 0;//счетчик кол-ва пешек ИИ на предверхней строчке(1-я)
        aicountthirdrow = 0;//счетчик кол-ва пешек ИИ на предпредверхней строчке(2-я)
    }

    https://github.com/Beginerok/DominiGames/blob/master/Domini/Chess/Chess/Game.cpp

    https://habr.com/ru/post/563398/
    Странные шахматы как тестовое задание

    PolinaAksenova, 18 Июня 2021

    Комментарии (175)
  4. C++ / Говнокод #27471

    +3

    1. 1
    2. 2
    3. 3
    //! Set this value as an empty object.
    /*! \post IsObject() == true */
    GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; }

    Парсер json'ок писали сверхлюди

    https://github.com/Tencent/rapidjson/blob/master/include/rapidjson/document.h#L1188

    mvngr, 16 Июня 2021

    Комментарии (27)
  5. C++ / Говнокод #27462

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    #include <iostream>
    #include <map>
    
    int main()
    {
      std::string name;
      std::map<int, int> m = { {1, 1}, {2, 2} };
      m.erase(m.end());
      std::cout << "Kokoko " << m[1] << std::endl;
    }

    На моем проекте уходит в бесконечный цикл.

    YpaHeLI_, 08 Июня 2021

    Комментарии (58)
  6. C++ / Говнокод #27456

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    // https://llvm.org/doxygen/AArch64AddressingModes_8h_source.html#l00051
    
     /// getShiftName - Get the string encoding for the shift type.
     static inline const char *getShiftExtendName(AArch64_AM::ShiftExtendType ST) {
       switch (ST) {
       default: llvm_unreachable("unhandled shift type!");
       case AArch64_AM::LSL: return "lsl";
       case AArch64_AM::LSR: return "lsr";
       case AArch64_AM::ASR: return "asr";
       case AArch64_AM::ROR: return "ror";
       case AArch64_AM::MSL: return "msl";
       case AArch64_AM::UXTB: return "uxtb";
       case AArch64_AM::UXTH: return "uxth";
       case AArch64_AM::UXTW: return "uxtw";
       case AArch64_AM::UXTX: return "uxtx";
       case AArch64_AM::SXTB: return "sxtb";
       case AArch64_AM::SXTH: return "sxth";
       case AArch64_AM::SXTW: return "sxtw";
       case AArch64_AM::SXTX: return "sxtx";
       }
       return nullptr;
     }

    Хорош ли тот язык, в котором такую херню надо писать?

    Именно поэтому я за гомоиконы.

    j123123, 06 Июня 2021

    Комментарии (56)
  7. C++ / Говнокод #27454

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    #include <iostream>
    using namespace std;
    
    int main() {
    	const char *kakoiBagor = R""""(
    "Какой
    багор )))"
    )"""";
    	cout << kakoiBagor << endl;
    	return 0;
    }

    А вы знали, что в C++ есть ХЕРЕДОК?

    https://ideone.com/5KdJJQ

    3_dar, 04 Июня 2021

    Комментарии (281)
  8. C++ / Говнокод #27450

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    int main(void)
    {
        std::string data = "HELLO WORLD!\n";
        std::transform(
            data.begin(), data.end(), 
            std::ostream_iterator<char>(std::cout, ""),
        std::bind(std::plus<char>(), std::placeholders::_1, 1));
        
        return 0;
    }

    А как сделать это ещё короче?

    digitalEugene, 02 Июня 2021

    Комментарии (10)
  9. C++ / Говнокод #27444

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    template<typename ReturnType, typename... Arguments>
    std::enable_if_t<!std::is_same_v<ReturnType, void>, std::deque<ReturnType>>
    emit(Event<ReturnType, Arguments...>& event, const std::tuple<Arguments...>& args)
    {
    	std::deque<ReturnType> toReturn;
    
    	for (auto&& c : event.subscribers | std::views::values)
    		toReturn.push_back(std::apply(c, args));
    
    	return toReturn;
    }
    
    template<typename ReturnType, typename... Arguments>
    void emit(Event<ReturnType, Arguments...>& event, const std::tuple<Arguments...>& args)
    {
    	for (auto&& c : event.subscribers | std::views::values)
    		std::apply(c, args);
    }

    кодить всё же надо трезвым.

    digitalEugene, 30 Мая 2021

    Комментарии (0)
  10. C++ / Говнокод #27443

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    // https://habr.com/ru/post/550442/
    // Как компилятор C++ находит правильную функцию 
    
    // Вот так компилятор точно определяет, какую функцию следует вызвать:
    // https://hsto.org/webt/mp/tb/5k/mptb5kheibrreqspserc4sfdfrs.png
    
    // Эти шаги закреплены в стандарте C++. Каждый компилятор C++ должен следовать им,
    // и все это происходит во время компиляции для каждого вызова функции. Оглядываясь
    // назад, это очевидно, что должен быть такой алгоритм. Это единственный способ, которым
    // C++ может поддерживать все вышеупомянутые возможности одновременно. Это то, что вы
    // получите, если необходимо объединить их вместе.
    
    // Я предполагаю, что общая цель алгоритма — «делать то, что ожидает программист»,
    // и до некоторой степени он в этом преуспевает. Вы можете довольно далеко зайти,
    // полностью игнорируя этот алгоритм. Но когда вы начинаете использовать все возможности
    // C++, как при разработке библиотеки, то лучше знать эти правила.

    Да, это конечно очень круто, только вот существует примерно 0 компиляторов, которые полностью корректно (т.е. в полном соответствии с Говностандартом) реализуют эту срань с вызовом правильной функции/метода с учетом всей хуйни.

    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51577 - этот баг висит еще 2011-12-16 и его так никто нихуя не пофиксил

    И в Clang такого рода баги тоже есть.

    j123123, 29 Мая 2021

    Комментарии (429)