C++ 命名需求: LiteralType (自 C++11 起)
來自 cppreference.com
指定一個型別是字面型別。字面型別是 constexpr
變數的型別,它們可以從 constexpr
函式中構造、操作和返回。
注意:標準沒有定義以此名稱命名的需求。這是一個由核心語言定義的型別類別。此處將其作為命名需求包含在內,僅為保持一致性。
目錄 |
[編輯] 要求
字面型別是以下任何一種
|
(C++14 起) |
- 具有一個 平凡(直到 C++20)constexpr(自 C++20 起) 解構函式,
- 其所有非靜態非變體資料成員和基類都是非 volatile 字面型別,並且
- 是以下之一
|
(C++17 起) |
[編輯] 注意
即使其所有 constexpr 建構函式被刪除、不可訪問或不能參與過載解析,型別也可以是字面型別。
struct A { constexpr A(int) = delete; char c; }; // A is a literal type constexpr A v = std::bit_cast<A>('0'); // OK in C++20 // v has literal type and thus can be constexpr
[編輯] 示例
擴充套件字串字面量的字面型別
執行此程式碼
#include <cstddef> #include <iostream> #include <stdexcept> class conststr // conststr is a literal type { const char* p; std::size_t sz; public: template<std::size_t N> constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {} constexpr char operator[](std::size_t n) const { return n < sz ? p[n] : throw std::out_of_range(""); } constexpr std::size_t size() const { return sz; } }; constexpr std::size_t count_lower(conststr s) { std::size_t c{}; for (std::size_t n{}; n != s.size(); ++n) if ('a' <= s[n] && s[n] <= 'z') ++c; return c; } // An output function that requires a compile-time constant N, for testing template<int N> struct constN { constN() { std::cout << N << '\n'; } }; int main() { std::cout << "The number of lowercase letters in \"Hello, world!\" is "; constN<count_lower("Hello, world!")>(); // the string literal is implicitly // converted to conststr }
輸出
The number of lowercase letters in "Hello, world!" is 9
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
CWG 1453 | C++11 | 字面量類可以有 volatile 資料成員 | 不允許 |
CWG 1951 | C++11 C++14 |
不清楚 cv 限定的 void (C++14) 和類型別 (C++11) 是否是字面型別 |
它們是 |
CWG 2096 | C++11 | 對於聯合型別要成為字面型別,其所有非- 靜態資料成員必須是字面型別 |
只有一個非靜態資料 成員需要是 |
CWG 2598 | C++11 | 對於聯合型別要成為字面型別,它必須有 至少一個非靜態資料成員 |
它可以沒有非- 靜態資料成員 |
[編輯] 另請參閱
(C++11)(C++17 中已棄用)(C++20 中已移除) |
檢查型別是否為字面型別 (類模板) |