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

    +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
    #include <iostream>
    #include <tuple>
    using namespace std;
    
    template<typename T, typename T0, typename T1, typename ...Args>
    void PrintStruct(const tuple<T0 T::*, T1 T::*, Args T::*...>& members, const T& val)
    {
    	cout << val.*std::get<0>(members) << endl;
    	PrintStruct(members._Get_rest(), val);
    }
    
    template<typename T, typename T0>
    void PrintStruct(const tuple<T0 T::*>& members, const T& val)
    {
    	cout << val.*std::get<0>(members) << endl;
    }
    
    struct MyStruct
    {
    	int x;
    	float y;
    
    	static const tuple<decltype(&MyStruct::x), decltype(&MyStruct::y)> Members;
    };
    
    const tuple<int MyStruct::*, float MyStruct::*> MyStruct::Members = std::make_tuple(&MyStruct::x, &MyStruct::y);
    
    int main()
    {
    	MyStruct str = {123, 3.14159f};
    	PrintStruct(MyStruct::Members, str);
    	return 0;
    }

    Пытался понять, почему мой код не компилится в 2013 студии, и быстренько накатал этот минимальный пример. Но вышел облом - он почему-то компилится, в отличие от моей реальной либы со схожими шаблонными крестоконструкциями.

    gammaker, 27 Июля 2016

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

    +8

    1. 1
    2. 2
    const
    #include "file.xpm"

    У чувака в файле file.xpm объявлен массив static char * icon_xpm [] = { "..", "..", ... } и он не может заинклудить его в плюсовый код. Вот такой воркараунд ему предложили.
    https://www.linux.org.ru/forum/development/10400992?cid=10406949

    kurwa-nextgen, 27 Июля 2016

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

    +3

    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
    #include <iostream>
     
    class A
    {
    public:
        virtual void print(int val = 10) { std::cout << "A" << val; }
    };
     
    class B : public A
    {
    public:
        virtual void print(int val = 20) { std::cout << "B" << val; }
    };
     
    int main()
    {
        B b;
        A& a = b;
        a.print();
        return 0;
    }

    when you see it, you’ll shit bricks

    Tonghost, 26 Июля 2016

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

    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
    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
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    // check that all selected vertices are one 3d vertex.
      bool UsedIndex = 0;
      bool IndexIsRegistered = false;
      for (int t = 0; t < Indices.count(); t++)
      {
        zUVVertex Vertex = OldVerts->at(t);
        if (!IndexIsRegistered)
        {
          IndexIsRegistered = true;
          UsedIndex = Vertex.BaseVertexIndex;
        }
        else if (UsedIndex != OldVerts->at(t).BaseVertexIndex)
        {
          // quit on fail
          return;
        }
      }
      NewList = new QList<zUVVertex>();
    
      zUVVertex NewVertex;
      bool VertexIsInitialized = false;
      bool CapIsHoled = false;
    
      for (quint32 t = 0; t < OldVerts->count(); t++)
      {
        bool Taked = false;
        for (quint32 j = 0; j < Indices.count(); j++)
        {
          if (OldVerts->at(t).index == Indices.at(j))
          {
            if (!VertexIsInitialized)
            {
              VertexIsInitialized = true;
              NewVertex = OldVerts->at(t);
            }
            Taked = true;
            NewVertex.IndicesBeforeWeld << t;
            break;
          }
        }
        if (!Taked)
        {
          (*NewList) << OldVerts->at(t);
        }
        else
        {
          zUVVertex Stub;
    
          if (!CapIsHoled)
          {
            Stub = NewVertex;
          }
          else
          {
            Stub.Index = 0x7FFFFFFF;
          }
          (*NewList) << Stub;
        }
      }
      (*NewList) << NewVertex;
    
      Taked = false;
      QList<zUVFace> *TempFacesList = new QList<zUVFace>();
    
      for (int t = 0; t < Faces->count(); t++)
      {
        zUVFace Face = Faces->at(t);
        zUVFace NewFace;
        for (int j = 0; j < Face.VertsIndices; j++)
        {
          quint32 Index0 = Face.VertsIndices.at(j);
          zUVVertex TestVertex = NewList->at(Index0);
          if (TestVertex.Index == 0x7FFFFFFF)
          {
            // need to replace
            NewFace = Faces->at(t);
            NewFace.VertsIndices.operator [](j) = NewList->count() - 1;
            Taked = true;
          }
        }
        if (Taked)
        {
          (*TempFacesList) << NewFace;
        }
      }

    http://www.gamedev.ru/code/forum/?id=216701

    gammaker, 25 Июля 2016

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

    +3

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    #include <windows.h>
    int main() {
    	HDC dc = CreateCompatibleDC (NULL);
    	SetLayout (dc, LAYOUT_RTL);
    	ScaleWindowExtEx (dc, -2147483647 - 1, -1, 1, 1, NULL);
    }

    bsod

    laMer007, 22 Июля 2016

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

    +4

    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
    void delslovo(char *a)
    {
        static int i = 0;
        static bool j = false;
        if (a[i++] != '\0')     delslovo(a);
        else i--;
        if (!j)
        {
            if (a[i] != ' '&&a[i] != '\n'&&a[i] != '\0')
            {
                j = true;
                i++;
            }
        }
        if (j)
        {
            if (a[i - 1] == ' ') return;
            a[i - 1] = a[i];
        }
        i--;
    }

    вот так надо удалять последнее слово из строки

    beckon, 22 Июля 2016

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

    +4

    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
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    #include <IO/Stream.h>
    #include "Algorithms/Range.h"
    #include "Algorithms/RangeConstruct.h"
    #include "Algorithms/RangeIteration.h"
    #include "Algorithms/RangeMutation.h"
    
    using namespace IO;
    using namespace Range;
    
    int main()
    {
      Console.PrintLine("Есть нормальная поддержка Юникода в консоли, даже на винде.");
      Console.PrintLine("Тестируется текст с кириллицей, греческим алфавитом αβγδεζηθικλμνξο, а также с иероглифами ㈇㌤㈳㌛㉨.");
      Console.PrintLine("Иероглифы не отображаются в консоли, потому что консольный шрифт их не содержит, но копируются оттуда нормально.");
    
       StringView strs[] = {"hello", "world"};
      StringView strs1[]  = {"range", "testing", "program"};
      StringView strs2[] = {"C++", "крут"};
    
      Console.PrintLine("В тесте используются три массива:", endl, strs, endl, strs1, endl, strs2);
      Console.PrintLine(endl, "Пример вывода initializer list:", endl, AsRange<double>({4353.435, 3243.23, 21.421, 12355.5, 64532}));
    
      auto fib = Recurrence(Algo::Op::Add<int>, 1, 1);
    
      Array<int> fibArr;
      fibArr.SetCountUninitialized(15);
      auto copyResult = fib.Take(15).Copy(fibArr());
      Console.PrintLine(endl, "Последовательность Фибоначчи в массиве: ", endl, fibArr());
      Console.PrintLine(endl, "Вторая половина того же массива задом наперёд: ", endl, fibArr($/2, $).Retro());
    
      fib.Drop(5).Take(15).Copy(fibArr.Insert($));
      Console.PrintLine(endl, "Добавляем 15 чисел Фибоначчи, начиная с пятого, в конец. Новое содержимое массива: ");
      Console.PrintLine(fibArr());
    
      Console.PrintLine(endl, "Объединяем элементы различных диапазонов в диапазоне кортежей: ", endl, ToString(
        Zip(
          fib.Take(30),
          Chain(AsRange(strs), AsRange(strs1), AsRange(strs2)).Cycle().Take(20),
          Recurrence([](int a, int b){return a*2+b;}, 1, 1).Take(17).Cycle().Drop(3).Take(22),
          fib.Take(19).Cycle().Drop(5).Take(50).Stride(3),
          Recurrence(Algo::Op::Mul<ulong64>, 2ull, 3ull).Take(9)
        ), 
        ",\n  ", "[\n  ", "\n]"));
    
    
      static const StringView pattern[] = {"pattern", "fills", "range"};
      Chain(AsRange(strs), AsRange(strs1), AsRange(strs2)).FillPattern(AsRange(pattern));
    
      Console.PrintLine(endl, "Поменяли сразу три массива одним вызовом FillPattern: ");
      Console.PrintLine(strs, endl, strs1, endl, strs2, endl);
    
      Console.PrintLine("11-й элемент зацикленного массива строк: ", endl, AsRange(strs).Cycle().Take(11).Tail(1), endl);
      Console.PrintLine("Перевёрнутый массив строк: ", endl, AsRange(strs).Retro(), endl);
      Console.PrintLine("Зациклили первые два элемента массива и взяли 10 из них:");
      Console.PrintLine(AsRange(strs1).Take(2).Cycle().Take(10) );
      Console.PrintLine("Между массивом строк и 5 числами Фибоначчи выбрали второе в рантайме: ");
      Console.PrintLine(Choose(AsRange(strs1), fib.Take(5).Map([](int x){return ToString(x);}), true) );
    
      static const size_t indices[] = {1,1,1,2,2,0,2,1,0};
      Console.PrintLine(
          RoundRobin(
            AsRange(strs1).Indexed(AsRange(indices)),
            Repeat(StringView("Test"), 5),
            AsRange(strs1),
            AsRange(strs2)
          ));
      
    
      Console.PrintLine(endl, "Введите строки, которые войдут в диапазон строк. В конце введите \"end\".");
      Console.PrintLine("Вы ввели следующие строки:", endl, ToString(Console.ByLine("end")) );
    
      int arr[]={1, 4, 11, 6, 8};
      Console.PrintLine("max{1, 4, 11, 6, 8} = ", AsRange(arr).Reduce(Algo::Op::Max<int>));
    
      Console.PrintLine("Генерация 100 случайных чисел от 0 до 999 и вывод квадратов тех из них, которые делятся на 7: ", endl,
        Generate([](){return math::urandom()%1000;}).Take(100)
        .Filter([](uint x) {return x%7==0;})
        .Map(math::sqr<uint>)
      );
    
      return 0;
    }

    Давно здесь не было моих велосипедов. А они с тех пор сильно эволюционировали, я даже многие фичи из языка D смог перенести в C++.
    Вывод в консоль и обсуждение здесь: http://www.gamedev.ru/flame/forum/?id=216045&page=99#m1481

    gammaker, 20 Июля 2016

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

    +7

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    #include <iostream>
    
    struct Test {
    	operator auto() -> bool { return true; }
    };
    
    int main() {
    	std::cout << std::boolalpha << Test() << std::endl;
    }

    operator auto() завезли!
    http://ideone.com/sGxeQn

    Antervis, 20 Июля 2016

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

    +3

    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
    #define __DEBUG
    #ifdef __DEBUG
        #define print_pair(p) do{std::cout << "(" << ((p).first + 1) << ", "\
                                << ((p).second + 1) << ")" << std::endl;}while(0);
    #endif
    
    Graph::result
    Graph::dijkstra (int start)
    {
    #ifdef __DEBUG
        std::cout << "Dijkstra algorithm tracing:" << std::endl;
    #endif
        distances[start] = 0;
        std::set<std::pair<int, int>> q;
        q.insert (std::make_pair(distances[start], start));
        while (!q.empty())
        {
    #ifdef __DEBUG
            std::cout << "top element of a set: ";
            print_pair(*q.begin());
    #endif
            int current = q.begin()->second;
            q.erase(q.begin());
            for (int i = 0; i < adj[current].size(); ++i)
            {
    #ifdef __DEBUG
        std::cout << "current vertex: " << (current + 1);
        std::cout << " ad current state of distances array is: " << std::endl;
        for (auto i: distances)
            std::cout << i << " ";
        std::cout << std::endl;
    #endif
                int to = adj[current][i].second;
                int length = adj[current][i].first;
                // Relaxations
                if (distances[to] > distances[current] + length)
                {
    #ifdef __DEBUG
        std::cout << "relaxation for edge (" << current << ", " << to << ") ";
        std::cout << "with weight " << length << std::endl;
    #endif
                    
                    q.erase(std::make_pair(distances[to], to));
                    distances[to] = distances[current] + length;
                    path[to] = current;
                    q.insert(std::make_pair(distances[to], to));
                }
            }
        }
        // Replace INF by -1
        std::replace (distances.begin(), distances.end(), INF, -1);
        return distances;
    }

    Я у мамы решил подебажить как мыщъх дебажил при помощи отладочной печати. Вот что получилось.

    HiewMorjowie, 18 Июля 2016

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

    +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
    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
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    96. 96
    97. 97
    98. 98
    99. 99
    #define CREATE_EVENT_LISTENER(_elname, arg1_type, arg1_name) \
    class _elname : public EventListener	 \
    {	 \
    private:	 \
    	class IContainer	 \
    		{	 \
    	public:	 \
    		virtual void Call(arg1_type arg1_name) = 0;	 \
    		virtual ~IContainer() {}	 \
    		};	 \
    	 \
    	class FunctionContainer : public IContainer	 \
    		{	 \
    	private:	 \
    		typedef void(*__CallbackPtr)(arg1_type);	 \
    	public:	 \
    		FunctionContainer(__CallbackPtr fn)	 \
    				{	 \
    			this->fn = fn;	 \
    				}	 \
    	 \
    		virtual void Call(arg1_type arg1_name)	 \
    				{	 \
    			fn(arg1_name);	 \
    				}	 \
    	 \
    	private:	 \
    		__CallbackPtr fn;	 \
    		};	 \
    		 \
    	template<class T, class Q>	 \
    	class MethodContainer : public IContainer	 \
    		{	 \
    	public:	 \
    		MethodContainer(T method, Q _this)	 \
    				{	 \
    			this->method = method;	 \
    			this->_this = _this;	 \
    				}	 \
    	 \
    		virtual void Call(arg1_type arg1_name )	 \
    				{	 \
    			(_this->*method)(arg1_name);	 \
    				}	 \
    	 \
    	private:	 \
    		T method;	 \
    		Q _this;	 \
    		};	 \
    public:	 \
    	typedef void(*__FN_CALLBACK)(arg1_type);	 \
    	 \
    	_elname(__FN_CALLBACK fn)	 \
    		{	 \
    		this->container = new FunctionContainer(fn);	 \
    		}	 \
    	 \
    	template <class T, class Q>	 \
    	_elname(T method, Q _this)	 \
    		{	 \
    		this->container = new MethodContainer<T, Q>(method, _this);	 \
    		}	 \
    	 \
    	void Call(arg1_type arg1_name)	 \
    		{	 \
    		container->Call(arg1_name);	 \
    		}	 \
    	 \
    	virtual ~_elname()	 \
    		{	 \
    		delete this->container;	 \
    		}	 \
    private:	 \
    	IContainer* container;	 \
    };	 \
    
    #define CREATE_EVENT(_ename, _elname, arg1_type, arg1_name) \
    class _ename : public Event	 \
    {	 \
    public:	 \
    	void AddListener(_elname* listener)	 \
    		{	 \
    		Event::AddListener(listener);	 \
    		}	 \
    	 \
    	void Handle(arg1_type arg1_name)	 \
    		{	 \
    		for (size_t i = 0; i < this->listeners.size(); i++)	 \
    												{	 \
    			((_elname*)listeners[i])->Call(arg1_name);	 \
    												}	 \
    		}	 \
    	 \
    	void RemoveListener(_elname* listener)	 \
    		{	 \
    		Event::RemoveListener(listener);	 \
    		}	 \
    	 \
    };	 \

    Я когда то это написал. Думал, это хорошая идея...
    Полный файл: https://github.com/arhyme/CPP_EVENTS/blob/master/Event.h

    Avery, 18 Июля 2016

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