- 1
https://en.cppreference.com/w/cpp/language/lambda
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
https://en.cppreference.com/w/cpp/language/lambda
> Explanation
> > <tparams>
> Like in a template declaration, the template parameter list may be followed by an optional requires-clause, which specifies the constraints on the template arguments.
> optional requires-clause
небязательные обязательные пункты.
Переводил почти час.
+3
// https://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case?__=1746193182#
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
Какой багор )))
+4
#include <inttypes.h>
auto a(auto b) __attribute__ ((noinline));
auto a(auto b)
{
return b*1.5;
}
double test1(double in)
{
return a(in);
}
uint64_t test2(uint64_t in)
{
return a(in);
}
/*
https://godbolt.org/z/6ZQAnv
auto a<double>(double):
mulsd xmm0, QWORD PTR .LC0[rip]
ret
test1(double):
jmp auto a<double>(double)
auto a<unsigned long>(unsigned long):
test rdi, rdi
js .L5
pxor xmm0, xmm0
cvtsi2sd xmm0, rdi
mulsd xmm0, QWORD PTR .LC0[rip] # хули ты мне плавучего питуха в xmm0 возвращаешь?
ret
.L5:
mov rax, rdi
and edi, 1
pxor xmm0, xmm0
shr rax
or rax, rdi
cvtsi2sd xmm0, rax
addsd xmm0, xmm0
mulsd xmm0, QWORD PTR .LC0[rip]
ret
test2(unsigned long):
sub rsp, 8
call auto a<unsigned long>(unsigned long)
movsd xmm1, QWORD PTR .LC1[rip]
comisd xmm0, xmm1
jnb .L8
cvttsd2si rax, xmm0 # ну нахуй тут надо double в uint64_t конвертить
add rsp, 8 # почему это не делается в auto a<unsigned long>(unsigned long)
ret
.L8:
subsd xmm0, xmm1
add rsp, 8
cvttsd2si rax, xmm0
btc rax, 63
ret
.LC0:
.long 0
.long 1073217536
.LC1:
.long 0
.long 1138753536
*/
концепты-хуепты
+1
template<typename T>
class IsClassT {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
// Will be chosen if T is anything except a class.
template<typename C> static Two test(...);
public:
enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
Как эта поебота работает?
Что такое "int C::*"?
+2
#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
−1
// 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,
Интересно, а эту херню кодогенерировали? Или это всё ручной труд?
+2
enet_uint32 flags = 0;
if (flags & CPacket::RELIABLE)
flags |=ENET_PACKET_FLAG_RELIABLE;
return enet_packet_create(data, (writer.Tell() + 7) / 8, flags);
Братишка сделал одинаковые названия локальной переменной и поля в классе.
+2
#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. Правда на момент написания я прошляпил, что речь шла о "нельзя возвращать массив"ю
+2
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 переменные, которые через ссылку или указатель пробрасывать можно, ну чисто чтоб поржать
+1
// 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.