Currently, I am using gcc, which allows the usage of a C variable length array in a C++ constexpr function (do not ask me why). This is, of course, not a standard behaviour, but results in the desired effect.
What I am searching for are more ways to emulate the desired behaviour in other compilers. As a standard fallback, I have included an option using unique_ptr, thus emulating gcc‘s behaviour on platforms that do not support constexpr and variable stack allocation.
Here is what I got so far:
class Integer {
private:
int i;
public:
constexpr
Integer(const int& _t = 10)
: i(_t)
{ }
constexpr int
get(void) const {
return i;
}
};
#if defined(__GNUC__) && !defined(__clang__)
#define XALLOC(type, name, count) type name[count]
#else
#include <memory>
#define XALLOC(type, name, count) std::unique_ptr<type[]> __##name(new type[count]); type* name = &__##name[0]
#endif
constexpr
int t(int num) {
XALLOC(Integer, i, num);
return i[0].get();
}
constinit int nu = t(10);
int main(int argc, const char *argv[]) {
return t(0);
}
I don't know if this will work in a
constexpr
function (haven't tried), but on most *nix platforms, you can allocate an arbitrary amount of space on the stack (well, up to a point...) withalloca
, e.g.C-style cast used for brevity, and the MSVC equivalent is
_alloca
(which you can solve with a simple, conditionally defined, macro).Please note that the Windows stack is only 1MB (although there's a linker flag to increase it), so mind how you go. Linux and others are 8MB, but again, there's probably a way to tweak it (and, in 64 bit builds, there's no real reason not to).
VLAs are non-standard and a little bit evil, do not use them.
An early Christmas present for @Red.Wave, this time not a poisoned chalice (sorry about that):