I want to create a class to better use strings in flash. At its core is the following
template<size_t N>
struct progstr
{
constexpr progstr(const char (&str)[N])
: progstr(str, make_index_sequence<N> {}) {}
template<size_t... Is>
constexpr progstr(const char (&str)[N], index_sequence<Is...>)
: _str{str[Is]...} {}
constexpr operator const char*() const {
return _str;
}
const char _str[N] PROGMEM;
};
Where make_index_sequence
and index_sequence
are the same as those from <utility>
.
The problem arises when I try to emulate PSTR
template<size_t N>
constexpr const char* pstr(const char (&str)[N])
{
return progstr<N>{str}; // huh?
}
It even compiles. However
The returned pointer is "dangling", but it is pointing into flash memory. Will this work?
A
constexpr
function may be called with an array with runtime values, and that cannot possibly create the string in flash can it?
1 Answer 1
I tested with 100 chars string
const char*
Sketch uses 1566 bytes
Global variables use 288 bytes
with F macro
Sketch uses 1594 bytes
Global variables use 188 bytes
progstr <101> ps(...
Sketch uses 1618 bytes
Global variables use 288 bytes
const char* ps = pstr("...
Sketch uses 1502 bytes
Global variables use 188 bytes
the pstr version string has errors at the end, when printed.
sorry, the pstr function works only if previous sketch version put the string into flash memory. it is not in hex file.
operator
keyword is missing in () operator