I have a class that contains a static constexpr
array of const char
s, which i would like to make available via a c_str()
method:
class my_class {
private:
static constexpr const char c_str_[6] = {'c', 'h', 'a', 'r', 's', '\0'};
public:
static constexpr const char* c_str() {
return c_str_;
}
};
This works, but has an unfortunate effect: It removes the length of the pointed-to array from the type:
decltype(my_class::c_str()) // equivalent to const char*
What I'd really like is some way to achieve this:
decltype(my_class::c_str()) // equivalent to const char[6]
I understand that in either case the returned object will be a pointer; I would just like to preserve the length of the pointed-to array in the type. Kind of like how decltype("string literal")
is const char[15]
, not const char*
.
Is there a way to do this?
You mean like returning a reference to c_str_
?
static constexpr decltype(c_str_)& c_str() { return c_str_; }
or
static constexpr auto& c_str() { return c_str_; }
If you want a pointer, just swap the &
for a *
and return &c_str_
.
If you want to explicitly refer to the type, use an alias:
using T = const char[6];
static constexpr T& c_str() { return c_str_; }
Or if you really hate yourself:
static constexpr const char (&c_str())[6] { return c_str_; }
Note that you cannot have a function return a raw array by value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With