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

    +2

    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
    #include <type_traits>
    
    struct Foo {
      void bar(int) const & {}
    };
    
    int main() {    
      using MethodPtr = decltype(&Foo::bar);
      const MethodPtr arr[] = { &Foo::bar };
      auto *ptr = &arr;
      auto &ref = ptr;
    
      static_assert(std::is_same_v<decltype(ref), void (Foo::* const (*&)[1])(int) const &>);
    }

    Магия указателей возведенная в степень магии массивов в степени магии ссылок.

    https://wandbox.org/permlink/8DygQ6oocrEY1K1M

    Elvenfighter, 11 Марта 2019

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

    −1

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    // Microsoft открыла код Калькулятора Windows
    
    // https://github.com/Microsoft/calculator/blob/057401f5f2b4bb1ea143da02c773ac18d1bb9a2e/src/CalcViewModel/Common/CalculatorButtonUser.h#L8
    
    namespace CalculatorApp
    {
        namespace CM = CalculationManager;
    
        public enum class NumbersAndOperatorsEnum
        {
            Zero = (int) CM::Command::Command0,
            One = (int) CM::Command::Command1,
            Two = (int) CM::Command::Command2,
            Three = (int) CM::Command::Command3,
            Four = (int) CM::Command::Command4,
            Five = (int) CM::Command::Command5,
            Six = (int) CM::Command::Command6,
            Seven = (int) CM::Command::Command7,
            Eight = (int) CM::Command::Command8,
            Nine = (int) CM::Command::Command9,
            Add = (int) CM::Command::CommandADD,
            Subtract = (int) CM::Command::CommandSUB,
            Multiply = (int) CM::Command::CommandMUL,
            Divide = (int) CM::Command::CommandDIV,
            Invert = (int) CM::Command::CommandREC,
            Equals = (int) CM::Command::CommandEQU,
            Decimal = (int) CM::Command::CommandPNT,
            Sqrt = (int) CM::Command::CommandSQRT,
            Percent = (int) CM::Command::CommandPERCENT,
            Negate = (int) CM::Command::CommandSIGN,
            Backspace = (int) CM::Command::CommandBACK,
            ClearEntry = (int) CM::Command::CommandCENTR,
            Clear = (int) CM::Command::CommandCLEAR,
            Degree = (int) CM::Command::CommandDEG,
            Radians = (int) CM::Command::CommandRAD,
            Grads = (int) CM::Command::CommandGRAD,
            Degrees = (int) CM::Command::CommandDegrees,
            OpenParenthesis = (int) CM::Command::CommandOPENP,
            CloseParenthesis = (int) CM::Command::CommandCLOSEP,
            Pi = (int) CM::Command::CommandPI,
            Sin = (int) CM::Command::CommandSIN,
            Cos = (int) CM::Command::CommandCOS,
            Tan = (int) CM::Command::CommandTAN,
            Factorial = (int) CM::Command::CommandFAC,
            XPower2 = (int) CM::Command::CommandSQR,
            Mod = (int) CM::Command::CommandMOD,
            FToE = (int) CM::Command::CommandFE,
            LogBaseE = (int) CM::Command::CommandLN,
            InvSin = (int) CM::Command::CommandASIN,
            InvCos = (int) CM::Command::CommandACOS,
            InvTan = (int) CM::Command::CommandATAN,
            LogBase10 = (int) CM::Command::CommandLOG,
            XPowerY = (int) CM::Command::CommandPWR,
            YRootX = (int) CM::Command::CommandROOT,
            TenPowerX = (int) CM::Command::CommandPOW10,
            EPowerX = (int) CM::Command::CommandPOWE,
            Exp = (int) CM::Command::CommandEXP,
            IsScientificMode = (int) CM::Command::ModeScientific,
            IsStandardMode = (int) CM::Command::ModeBasic,
            None = (int) CM::Command::CommandNULL,
            IsProgrammerMode = (int) CM::Command::ModeProgrammer,
            DecButton = (int) CM::Command::CommandDec,
            OctButton = (int) CM::Command::CommandOct,
            HexButton = (int) CM::Command::CommandHex,
            BinButton = (int) CM::Command::CommandBin,
            And = (int) CM::Command::CommandAnd,
            Ror = (int) CM::Command::CommandROR,
            Rol = (int) CM::Command::CommandROL,
            Or = (int) CM::Command::CommandOR,
            Lsh = (int) CM::Command::CommandLSHF,
            Rsh = (int) CM::Command::CommandRSHF,
            Xor = (int) CM::Command::CommandXor,
            Not = (int) CM::Command::CommandNot,
            A = (int) CM::Command::CommandA,
            B = (int) CM::Command::CommandB,
            C = (int) CM::Command::CommandC,
            D = (int) CM::Command::CommandD,
            E = (int) CM::Command::CommandE,
            F = (int) CM::Command::CommandF,
            Memory, // This is the memory button. Doesn't have a direct mapping to the CalcEngine.        
            Sinh = (int) CM::Command::CommandSINH,
            Cosh = (int) CM::Command::CommandCOSH,
            Tanh = (int) CM::Command::CommandTANH,
            InvSinh = (int) CM::Command::CommandASINH,
            InvCosh = (int) CM::Command::CommandACOSH,
            InvTanh = (int) CM::Command::CommandATANH,
            Qword = (int) CM::Command::CommandQword,
            Dword = (int) CM::Command::CommandDword,
            Word = (int) CM::Command::CommandWord,
            Byte = (int) CM::Command::CommandByte,
            Cube = (int) CM::Command::CommandCUB,
            DMS = (int) CM::Command::CommandDMS,
    
            BINSTART = (int) CM::Command::CommandBINEDITSTART,
            BINPOS0 = (int) CM::Command::CommandBINPOS0,
            BINPOS1 = (int) CM::Command::CommandBINPOS1,
            BINPOS2 = (int) CM::Command::CommandBINPOS2,
            BINPOS3 = (int) CM::Command::CommandBINPOS3,
            BINPOS4 = (int) CM::Command::CommandBINPOS4,
            BINPOS5 = (int) CM::Command::CommandBINPOS5,

    Интересно, а эту херню кодогенерировали? Или это всё ручной труд?

    j123123, 09 Марта 2019

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

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    enet_uint32 flags = 0;
    
    if (flags & CPacket::RELIABLE)
        flags |=ENET_PACKET_FLAG_RELIABLE;
    
    return enet_packet_create(data, (writer.Tell() + 7) / 8, flags);

    Братишка сделал одинаковые названия локальной переменной и поля в классе.

    tuxick, 03 Марта 2019

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

    +2

    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
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    #include <tuple>
    #include <utility>
    #include <array>
    
    namespace detail {
    
    template <typename... Types, std::size_t... Indexes>
    auto make_array(const std::tuple<Types...> &t, std::index_sequence<Indexes...>) {
       using Tuple = std::tuple<Types...>;
       using ValueType = typename std::tuple_element<0, Tuple>::type;
       return std::array<ValueType, sizeof...(Types)>{ std::get<Indexes>(t)... };
    }
    
    template <typename Value>
    constexpr Value fib(std::size_t idx) {
      switch (idx) {
      case 0: return 1;
      case 1: return 1;
      default: return fib<Value>(idx - 1) + fib<Value>(idx - 1);
      }
    }
    }
    
    template <class... Args>
    auto to_array(const std::tuple<Args...> &t) {
      return detail::make_array(t, std::index_sequence_for<Args...>{});
    }
    
    template <typename Value, std::size_t size>
    class Fibonacci {
    public:
      constexpr auto as_array() const { return to_array(as_tuple()); }
     
      constexpr operator std::array<Value, size>() const { return as_array(); }
      
    private:
      template <std::size_t offset = 0> 
      constexpr auto as_tuple() const {
        return std::tuple_cat(std::tuple{detail::fib<Value>(offset)}, as_tuple<offset + 1>());
      }
      
      template <>
      constexpr auto as_tuple<size - 1>() const { return std::tuple{detail::fib<Value>(size - 1)}; }
    };
    
    int main() {
      std::array a = Fibonacci<int, 10>().as_array();
      return a[5];
    }

    По мотивам http://govnokod.ru/25401#comment460820. Правда на момент написания я прошляпил, что речь шла о "нельзя возвращать массив"ю

    Elvenfighter, 25 Февраля 2019

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

    +2

    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
    constexpr void foo(int &a, const int b)
    {
      a = b * 2;
    }
    
    constexpr void foo2(int *a, const int b)
    {
      *a = b * 2;
    }
    
    constexpr int shit = []() constexpr {int a = 0; foo(a, 666); return a;}();
    
    constexpr int shit2 = []() constexpr {int a = 0; foo2(&a, 666); return a;}();

    Итак, время обсирать крестоговно. Вот есть там такая фича - можно по ссылке и указателю хуйню через constexpr присваивать. Только вот эта тупая херня под названием лямбда, она обязательно требует инициализации некоторого говна, передаваемого куда-то там, если она объявлена как constexpr. На кой хрен мне что-то инициализировать, если это говно я в constexpr не читаю, а только присваиваю? И сделайте там какие-нибудь write-only переменные, которые через ссылку или указатель пробрасывать можно, ну чисто чтоб поржать

    j123123, 23 Февраля 2019

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

    +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
    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
    // https://github.com/CVC4/CVC4/blob/14b9dbaa0c9e8dce52d1a28595dc1cc80756abed/src/expr/pickler.cpp
    
    
    static Block mkBlockBody4Chars(char a, char b, char c, char d) {
      Block newBody;
      newBody.d_body.d_data = (a << 24) | (b << 16) | (c << 8) | d;
      return newBody;
    }
    
    static char getCharBlockBody(BlockBody body, int i) {
      Assert(0 <= i && i <= 3);
    
      switch(i) {
      case 0: return (body.d_data & 0xff000000) >> 24;
      case 1: return (body.d_data & 0x00ff0000) >> 16;
      case 2: return (body.d_data & 0x0000ff00) >> 8;
      case 3: return (body.d_data & 0x000000ff);
      default:
        Unreachable();
      }
      return '\0';
    }
    
    // ...
    
    void PicklerPrivate::toCaseString(Kind k, const std::string& s) {
      d_current << mkConstantHeader(k, s.size());
    
      unsigned size = s.size();
      unsigned i;
      for(i = 0; i + 4 <= size; i += 4) {
        d_current << mkBlockBody4Chars(s[i + 0], s[i + 1],s[i + 2], s[i + 3]);
      }
      switch(size % 4) {
      case 0: break;
      case 1: d_current << mkBlockBody4Chars(s[i + 0], '\0','\0', '\0'); break;
      case 2: d_current << mkBlockBody4Chars(s[i + 0], s[i + 1], '\0', '\0'); break;
      case 3: d_current << mkBlockBody4Chars(s[i + 0], s[i + 1],s[i + 2], '\0'); break;
      default:
        Unreachable();
      }
    
    }

    Очередное переизобретение какой-то байтоебской поеботы типа ntohl(). И вообще, тут UB.

    j123123, 21 Февраля 2019

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

    +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
    // https://habr.com/ru/post/440388/
    // Интервалы: грядущая эволюция C++ 
    
    // Давайте теперь рассмотрим следующую задачу: имеется вектор, необходимо удалить
    // из него все повторяющиеся элементы. В рамках текущего стандарта мы решали бы её так:
    
    std::vector<T> vec=...;
    std::sort( vec.begin(), vec.end() );
    vec.erase( std::unique( vec.begin(), vec.end() ), vec.end() );
    
    
    // При этом мы указываем имя вектора аж 6 раз! Однако, используя концепцию интервалов
    // (объединив итераторы на начало и конец вектора в один объект), можно написать в разы проще, указав искомый вектор лишь единожды:
    
    tc::unique_inplace( tc::sort(vec) );
    
    //... Че, серьезно? Я так тоже могу:
    // Однако, используя сишный препроцессор™, можно написать в разы проще, указав искомый вектор лишь единожды:
    
    #define DELETE_DUPS(x) do{ std::sort( x.begin(), x.end() ); x.erase( x::unique( x.begin(), x.end() ), x.end() );}while(0)
    
    DELETE_DUPS(vec);

    Тоже мне революция.

    j123123, 15 Февраля 2019

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

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    #pragma once
    
    #define ENUM_DECLARE_BEGIN(enum_class, enum_value) \
    class enum_class##__enum__##enum_value : public enum_class {
    
    #define ENUM_DECLARE_END(enum_class, enum_value) \
    }; extern const enum_class##__enum__##enum_value enum_value;
    
    #define ENUM_DEFINE(enum_class, enum_value, enum_namespace) const enum_class##__enum__##enum_value enum_namespace enum_value;

    UsernameAK, 10 Февраля 2019

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

    +4

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    struct Data { /* ... */ };
    
    class Items {
      void insert(Data&& data) {
        _storage.emplace_back(std::forward<Data>(data));
      }
    private:
      std::vector<Data> _storage;
    };

    Dumb luck. Nuff said.

    Elvenfighter, 08 Февраля 2019

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

    +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
    // https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
    
    // The Curiously Recurring Template Pattern (CRTP)
    template<class T>
    class Base
    {
        // methods within Base can use template to access members of Derived
    };
    class Derived : public Base<Derived>
    {
        // ...
    };

    > The Microsoft Implementation of CRTP in Active Template Library (ATL) was independently discovered, also in 1995 by Jan Falkin who accidentally derived a base class from a derived class. Christian Beaumont, first saw Jan's code and initially thought it couldn't possibly compile in the Microsoft compiler available at the time. Following this revelation that it did indeed work, Christian based the entire ATL and Windows Template Library (WTL) design on this mistake.

    А какая ошибка по-вашему положена в основу всего дизайна языка C++?

    j123123, 06 Февраля 2019

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