Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ functions return a pointer to an array of known length?

I have a class that contains a static constexpr array of const chars, 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?

like image 232
SumDood Avatar asked Dec 17 '22 19:12

SumDood


1 Answers

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.

like image 139
Barry Avatar answered Dec 28 '22 22:12

Barry