简体   繁体   中英

How to place user-defined literal inside constexpr class of same type in C++?

I want to implement my own string-literal class Literal and operator:

constexpr Literal operator""_s(const char* str, size_t size);

class Literal {
  friend constexpr Literal operator"" _s(const char*, size_t);

  constexpr Literal(const char* str, size_t size);

  const char* str = nullptr;
  const size_t size = 0u;
};

Then I want to place an empty literal inside my class:

class Literal {
  …
  static constexpr const Literal empty = ""_s;
  …
};

As expected compiler refuses such construction because class is incomplete at this point. Also I suggest that it's technically should be possible, since the compiler just needs to put somewhere the pair of char* str = nullptr and size_t size = 0 for the empty literal and assign it at compile-time to the static instance of my class.

Is there some "trick" to achieve the clause like: auto new_literal = Literal::empty; ?

Is there some "trick" to achieve the clause like: auto new_literal = Literal::empty; ?

You can add a static member function,

class Literal {
  // …
  static constexpr Literal empty() { return ""_s; }
  // …
}

, and use it like

constexpr auto new_literal = Literal::empty();

However, note that

static_assert("" != nullptr);
static_assert(""[0] == '\0');

No, there is no such trick. This example is no different from

struct X;
constexpr X getx();

struct X {
    static constexpr X x = getx();

};

Incomplete classes can't be used as constexpr variables, as, per standard,

A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized.

At this point, compiler doesn't even know if the type is a literal type, so it can't accept incomplete class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM