Created
May 28, 2021 19:27
-
-
Save paxbun/04c25b0bd88c2b21a5533a46a9677584 to your computer and use it in GitHub Desktop.
C++20 string as non-type template argument example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| struct String | |
| { | |
| const char* str; | |
| constexpr String(const char* str) : str { str } {} | |
| constexpr operator const char*() const | |
| { | |
| return str; | |
| } | |
| }; | |
| template <String string> | |
| constexpr size_t StringLength() | |
| { | |
| size_t rtn = 0; | |
| while (string[rtn]) ++rtn; | |
| return rtn; | |
| } | |
| int main() | |
| { | |
| char str[StringLength<"Hello">()] = "Hell"; | |
| static_assert(sizeof str == 5); | |
| std::cout << str << " world!\n"; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment