【发布时间】:2020-03-12 16:31:53
【问题描述】:
我们被限制为不能在程序中使用循环作为编程挑战。
限制: 不能使用 while、for、goto 和递归。
这些限制非常令人生畏。我真的想不出任何合适的解决方案。 所以我选择了这个通过修改返回地址实现的。
这会更好吗?
#include <unistd.h>
#include <sys/mman.h>
#include <iostream>
#include <cstring>
void the__(){}
void magic__(){}
void loop__(){}
void function__(){}
void here__(){}
template <typename T>
struct for_
{
bool started = false;
void* fix = nullptr;
void(*body)(T&) = nullptr;
for_(void(*body)(T&))
: body(body)
{
auto do_for__ = uintptr_t(do_for_);
uint64_t magic[] = {5243466812662057800, 6135086863767628931ull, 10416984888688609608ull, 144};
mprotect((void*)(do_for__-do_for__%4096), 4096, 7);
std::memcpy((void*)(do_for__+135), magic, 25);
}
static void do_for_(T& ctx)
{
void** p = (void**)((char*)&p+16);
if (!ctx.started)
{
if (!ctx) return;
ctx.started = true;
ctx.fix = *p;
*p = (void*)do_for_;
}
ctx.body(ctx);
ctx.next();
if (ctx)
{
the__();
magic__();
loop__();
function__();
here__();
}
else
{
*p = ctx.fix;
}
}
};
struct For0ToN : for_<For0ToN>
{
For0ToN(int N, void(*f)(For0ToN&))
: for_<For0ToN>(f)
, N(N)
{
do_for_(*this);
}
operator bool() {return i < N;}
operator int() {return i;}
void next() {i++;}
int count() {return i;}
int i = 0, N = 0;
};
int main()
{
For0ToN(10, +[](For0ToN& i)
{
std::cout << int(i) << ": ";
For0ToN(i.count(), +[](For0ToN& i)
{
std::cout << int(i) << ". ";
});
std::cout << "\n";
});
std::cout << "done\n";
return 0;
}
代码在这里演示:https://coliru.stacked-crooked.com/a/3dd77ade501ac748
【问题讨论】:
-
您提到了限制,但没有提到您的实际任务。你想解决什么问题?
-
阅读
setjmp/longjmp。然后立即忘记你读过的所有内容。 -
这个限制是谁设置的?上下文是什么?如果这是针对特定类或其他东西,则可能有一种“预期”的方式来执行此操作。
-
在编译时循环中使用模板会受到递归的限制吗?见medium.com/@savas/…
-
这是一种古老的智慧训练,你会发现循环一直在你的内部?
标签: c++