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

    +153

    1. 1
    2. 2
    3. 3
    4. 4
    auto L = [](int i)->int { return i+1; };
    typedef decltype(L) TL;
    auto lfunc = &TL::operator();
    int i = (L.*lfunc)(1);

    ohlol, 08 Октября 2011

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

    +160

    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
    #include <iostream>
     
    int main()
    {
    int a[4] = {1,2,3,4}; 
    int (&b)[4] = a; 
    int c[4] = {5,6,7,8}; 
    a=c; 
    std::cout<<b[0];
    }
    
    prog.cpp: In function ‘int main()’:
    prog.cpp:8: error: invalid array assignment

    Да, похоже С++ не настолько высокоуровневый, чтобы поддерживать такое понятие как присваивание массивов.

    http://www.gamedev.ru/flame/forum/?id=153265&page=2#m20

    TarasB, 08 Октября 2011

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

    +157

    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
    #include <iostream>
    #include <boost/mpl/pair.hpp>
    #include <boost/mpl/key_type.hpp>
    #include <boost/mpl/map.hpp>
    #include <boost/mpl/string.hpp>
    #include <boost/mpl/for_each.hpp>
    using namespace boost;
    typedef mpl::map<
       mpl::pair<mpl::string<'H','e','l','l','o'>, mpl::int_<0>>,
       mpl::pair<mpl::string<',',' '>, mpl::int_<1>>,
       mpl::pair<mpl::string<'W','o','r','l','d','!'>, mpl::int_<2>>
    > map;
    struct do_some {
       template<typename T>
       void operator()(T) const {
          std::cout << mpl::c_str<T>::value;
       }
    };
    int main() {
       mpl::for_each<
          map,
          typename mpl::lambda<
             mpl::key_type<map, mpl::_1>
          >
       >(do_some());
    }

    еще один хеловорд.

    niXman, 08 Октября 2011

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

    +154

    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
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    class Allocator
    {
    public:
      
      virtual void *Alloc (size_t) = 0;
      virtual void Dealloc (void *) = 0;
    
      struct Allocation
      {
        Allocator *m_pAllocator[1];
    
        static void Dealloc (void *ptr)
        {
          if (ptr)
            ((Allocator **)ptr)[-1]->Dealloc (((Allocator **)ptr)-1);
        }
      };
    };
    
    class UsesAllocator
    {
    public:
      void *operator new (size_t aSize,Allocator &aAllocator)
      {
        Allocator::Allocation *pResult =
          (Allocator::Allocation *)
          aAllocator.Alloc (aSize+sizeof (Allocator::Allocation));
        if (!pResult) throw std::bad_alloc ();
        pResult->m_pAllocator[0] = &aAllocator;
        return pResult->m_pAllocator+1;
      }
    
      void *operator new [] (size_t aSize,Allocator &aAllocator)
      {
        Allocator::Allocation *pResult =
          (Allocator::Allocation *)
          aAllocator.Alloc (aSize+sizeof (Allocator::Allocation));
        if (!pResult) throw std::bad_alloc ();
        pResult->m_pAllocator[0] = &aAllocator;
        return pResult->m_pAllocator+1;
      }
    
      void operator delete (void *ptr,Allocator &)
      { Allocator::Allocation::Dealloc (ptr); }
    
      void operator delete (void *ptr)
      { Allocator::Allocation::Dealloc (ptr); }
    
      void operator delete [] (void *ptr,Allocator &)
      { Allocator::Allocation::Dealloc (ptr); }
    
      void operator delete [] (void *ptr)
      { Allocator::Allocation::Dealloc (ptr); }
    };
    ...
    
    class MyClass: /*virtual*/ public UsesAllocator
    {
    public:
      ...
    };
    ...
    MyClass *PROFIT = new (allocatorOfOurInterest) MyClass (...);

    http://www.gamedev.ru/flame/forum/?id=153274

    >Посоны! Оказывается, оператор new можно перегружать!

    ohlol, 08 Октября 2011

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

    +167

    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
    #define BREAKABLE_SECTION() for(;;)
    
    BREAKABLE_SECTION()
    {
        ::Packet * pPacket;
        res = ReadPacket(pPacket);
    
        if(ERR_OK == res)
        {
            res = pConstructor->PutPacket(pPacket);
    
            if(ERR_OK == res)
            {
                res = pConstructor->GetFrame(data);
            }else
            {
                //TODO:add handler of statuses other than err_ok
            }
    
            if (ERR_OK ==res)
            {
                break;
            }else
            {
                //TODO:add handler of statuses other than err_ok
            }
        }else
        {
            break;
        }
        break;
    }

    перешел в новый проект где предложили изучить существующий код в огромном объеме - а он весь из таких циклов

    openclgovno, 06 Октября 2011

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

    +163

    1. 1
    2. 2
    3. 3
    4. 4
    if ((intPas1Sel == 1) && (intMode11+intMode12    > 0)) { tgt [tgtNum].c1=tgtCode [prTgt [j].Num][0]; h2=h2 | 0x800 ; h1=h1 | (s << 12); }
    			if ((intPas2Sel == 1) && (intMode2               > 0)) { tgt [tgtNum].c3=tgtCode [prTgt [j].Num][1]; h2=h2 | 0x1000; h1=h1 | (s << 10); }
    			if ((intPas3ASel== 1) && (intMode3A1+intMode3A2  > 0)) { tgt [tgtNum].c3=tgtCode [prTgt [j].Num][2]; h2=h2 | 0x2000; h1=h1 | (s << 8 ); }
    			if ((intSecOver == 0) && (prTgt [j].unStateIdent > 0)) { tgt [tgtNum].cc=tgtCode [prTgt [j].Num][3]; h2=h2 | 0x8000; h1=h1 | (s << 14); }

    Так форматируют код профессионалы в нашей фирме

    russian_avionics, 04 Октября 2011

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

    +149

    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
    #include <iostream>
    
    struct empty_struct{};
    
    template<char S, typename N>
    struct char_type
    {
    	static const char value = S;
    	typedef N next;
    };
    
    typedef
    	char_type<'h', 
    	char_type<'e',
    	char_type<'l',
    	char_type<'l',
    	char_type<'o',
    	char_type<' ',
    	char_type<'w',
    	char_type<'o',
    	char_type<'r',
    	char_type<'l',
    	char_type<'d',
    	char_type<'!',
    	char_type<'\n', empty_struct> > > > > > > > > > > > > data_type;
    
    template<typename T>
    void print()
    {
    	std::cout << T::value;
    	print<T::next>();
    }
    
    template<>
    void print<empty_struct>()
    {
    }
    
    int main(int argc, char* argv[])
    {
    	print<data_type>();
    
    	return 0;
    }

    Такой простой hello world!

    AxisPod, 03 Октября 2011

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

    +164

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    // DIE, you, nasty context!
        while(GetLastError()!=0)
        {
            //You will soon become NON-BUSY!
            SetLastError(0);
            wglDeleteContext(glcontext);
            std::cout<<GetLastError()<<"\n";
        }

    Trying to delete my busy OpenGL context from other thread ;]

    petersvp, 03 Октября 2011

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

    +170

    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
    #include <stdio.h>
    #include <math.h>
    #include <conio.h>
    int main()
    { //ввод исходных данных
    short int i, j, k, l;
    printf("i="); scanf("%d",&i);
    printf("j="); scanf("%d",&j);
    printf("k="); scanf("%d",&k);
    printf("l="); scanf("%d",&l);
    if ((k==i+2) && (l==j+1)); else
    if ((k==i+2) && (l==j-1)); else
    if ((k==i-2) && (l==j+1)); else
    if ((k==i-2) && (i==j-1)); else
    if ((k==j+2) && (l==i+1)); else
    if ((k==j+2) && (l==i-1)); else
    if ((k==j-2) && (l==i+1)); else
    if ((k==j-2) && (l==i-1))
    printf("k= %d", k);
    printf("l= %d", l);
    //конь встал на нужную точку
    getch();
    }

    http://otvet.mail.ru/question/64546141/

    vkontakte, 02 Октября 2011

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

    +155

    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
    #include <iostream>
    #include <memory>
    #include <assert.h>
    using namespace std;
     
    template <class T>
    class megaClass
    {
    public:
     
        void hello()
        {
            assert(dynamic_cast<T*>(this)!=NULL);
            static_cast<T*>(this)->hello();
        }
        virtual ~megaClass() {}
    };
     
    class cleft : public megaClass<cleft>
    {
    public:
     
        void hello()
        {
            std::cout << "left::hello()" << std::endl;
        }
    };
     
    class cright : public megaClass<cright>
    {
    public:
     
        void hello()
        {
            std::cout << "right::hello()" << std::endl;
        }
    };
     
     
    int main()
    {
        scoped_ptr<megaClass<cleft> > a1=new cleft;
        a1->hello();
        scoped_ptr<megaClass<cright> > a2=new cright;
        a2->hello();
        
        return 0;
    }

    Пытался продемонстрировать статический полиморфизм TarasB и получилась такая какашка. Кто действительно крут и может сабдж продемонстрировать? Я где-то видел пример, но не помню где...

    Ещё продемонстрировал статический полиморфизм через стратегии:

    struct Strategy1
    {
    static void do(){printf("Lol1");}
    };
    struct Strategy2
    {
    static void do(){printf("Lol2");}
    };
    template<class Strategy>
    class MegaClass
    {public:
    void do()
    {
    printf("Mega");
    Strategy::do();//Класс Strategy можно было и создать для хранения состояния.
    printf("/n\");
    }
    };
    //...

    Дальше в разных частях кода создаем:
    MegaClass<Strategy1> o;
    o.do();
    //...
    MegaClass<Strategy2> o;
    o.do();
    "Один" класс ведёт себя по разному. Понятно, что это не совсем полиморфизм. Но очень часто именно в таком контексте используют динамический полиморфизм, хотя такого статического здесь достаточно выше крыши.
    Плюсы этого подхода :
    1)Создаётся объект в стеке, значит быстро, а не в куче. Хотя можно и не в стеке.
    2)Используется шаблон, значит компиль будет инлайнить.

    Минус:
    1)Если понадобится резкой перейти от статического полиморфизма к динамическому - придётся переписывать на виртуальные функции или на истинный статический полиморфизм.

    Обсуждения здесь:
    http://govnokod.ru/8025#comment110773


    Сразу исключим детсадовский вариант статического функционального полиморфизма c перегрузкой функций:
    Class1 o1;
    foo(o1);
    Class2 o2;
    foo(o2);

    void foo(Class1 o){/*...*/};
    void foo(Class2 o){/*...*/};



    Кто-нибудь реально умеет can into нормальный статический полиморфизм?

    CPPGovno, 30 Сентября 2011

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