- 1
- 2
- 3
- 4
auto L = [](int i)->int { return i+1; };
typedef decltype(L) TL;
auto lfunc = &TL::operator();
int i = (L.*lfunc)(1);
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+153
auto L = [](int i)->int { return i+1; };
typedef decltype(L) TL;
auto lfunc = &TL::operator();
int i = (L.*lfunc)(1);
+160
#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
+157
#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());
}
еще один хеловорд.
+154
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+167
#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;
}
перешел в новый проект где предложили изучить существующий код в огромном объеме - а он весь из таких циклов
+163
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); }
Так форматируют код профессионалы в нашей фирме
+149
#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!
+164
// 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 ;]
+170
#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/
+155
#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();"Один" класс ведёт себя по разному. Понятно, что это не совсем полиморфизм. Но очень часто именно в таком контексте используют динамический полиморфизм, хотя такого статического здесь достаточно выше крыши.http://govnokod.ru/8025#comment110773Class1 o1;
foo(o1);
Class2 o2;
foo(o2);
void foo(Class1 o){/*...*/};
void foo(Class2 o){/*...*/};