|
| 1 | +# is_string_literal |
| 2 | +* meta[meta header] |
| 3 | +* std[meta namespace] |
| 4 | +* function[meta id-type] |
| 5 | +* cpp26[meta cpp] |
| 6 | + |
| 7 | +```cpp |
| 8 | +namespace std { |
| 9 | + consteval bool is_string_literal(const char* p); // (1) C++26 |
| 10 | + consteval bool is_string_literal(const wchar_t* p); // (2) C++26 |
| 11 | + consteval bool is_string_literal(const char8_t* p); // (3) C++26 |
| 12 | + consteval bool is_string_literal(const char16_t* p); // (4) C++26 |
| 13 | + consteval bool is_string_literal(const char32_t* p); // (5) C++26 |
| 14 | +} |
| 15 | +``` |
| 16 | +
|
| 17 | +## 概要 |
| 18 | +ポインタが文字列リテラル(またはそのサブオブジェクト)を指しているかどうかを判定する。 |
| 19 | +
|
| 20 | +主に[`reflect_constant_string()`](reflect_constant_string.md)の内部実装で使用される。`reflect_constant_string()`は入力が既にヌル終端された文字列リテラルであればヌル終端文字を追加せず、そうでなければ追加する必要があるため、この関数で文字列リテラルかどうかを判定する。 |
| 21 | +
|
| 22 | +ユーザーが直接使用する場合は、`const char*`の出自をコンパイル時に検査して、文字列リテラルに由来するポインタとそうでないポインタを区別する用途が考えられる。 |
| 23 | +
|
| 24 | +- (1) : 通常の文字列リテラル(`"hello"`)を判定する |
| 25 | +- (2) : ワイド文字列リテラル(`L"hello"`)を判定する |
| 26 | +- (3) : UTF-8文字列リテラル(`u8"hello"`)を判定する |
| 27 | +- (4) : UTF-16文字列リテラル(`u"hello"`)を判定する |
| 28 | +- (5) : UTF-32文字列リテラル(`U"hello"`)を判定する |
| 29 | +
|
| 30 | +
|
| 31 | +## 戻り値 |
| 32 | +`p`が文字列リテラルまたはそのサブオブジェクトを指している場合に`true`を返す。そうでなければ`false`を返す。 |
| 33 | +
|
| 34 | +
|
| 35 | +## 備考 |
| 36 | +この関数は`std`名前空間に定義される(`std::meta`名前空間ではない)。 |
| 37 | +
|
| 38 | +
|
| 39 | +## 例 |
| 40 | +```cpp example |
| 41 | +#include <meta> |
| 42 | +#include <print> |
| 43 | +
|
| 44 | +// 文字列リテラルならそのまま使い、そうでなければコピーして使う |
| 45 | +consteval const char* ensure_static(const char* p) { |
| 46 | + if (std::is_string_literal(p)) { |
| 47 | + return p; // 文字列リテラルは静的ストレージに既に存在する |
| 48 | + } |
| 49 | + return std::define_static_string(std::string_view(p)); |
| 50 | +} |
| 51 | +
|
| 52 | +int main() { |
| 53 | + // 文字列リテラル |
| 54 | + constexpr auto s1 = ensure_static("hello"); |
| 55 | + std::println("{}", s1); |
| 56 | +
|
| 57 | + // 文字列リテラルの部分文字列(サブオブジェクト) |
| 58 | + static_assert(std::is_string_literal("hello" + 2)); // "llo"を指す |
| 59 | +} |
| 60 | +``` |
| 61 | +* std::is_string_literal[color ff0000] |
| 62 | +* std::define_static_string[link define_static_string.md] |
| 63 | + |
| 64 | +### 出力 |
| 65 | +``` |
| 66 | +hello |
| 67 | +``` |
| 68 | + |
| 69 | +## バージョン |
| 70 | +### 言語 |
| 71 | +- C++26 |
| 72 | + |
| 73 | +### 処理系 |
| 74 | +- [Clang](/implementation.md#clang): ?? |
| 75 | +- [GCC](/implementation.md#gcc): ?? |
| 76 | +- [Visual C++](/implementation.md#visual_cpp): ?? |
| 77 | + |
| 78 | + |
| 79 | +## 関連項目 |
| 80 | +- [`define_static_string`](define_static_string.md) |
| 81 | + |
| 82 | + |
| 83 | +## 参照 |
| 84 | +- [P3491R3 `define_static_{string,object,array}`](https://open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3491r3.html) |
0 commit comments