From f4675ed641157632cecbed8cd3ee82ed72594ffb Mon Sep 17 00:00:00 2001 From: Neargye Date: Tue, 7 Aug 2018 21:13:40 +0500 Subject: [PATCH] improve cstring --- example/example.cpp | 2 +- include/nameof.hpp | 26 ++++++++++++-------------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 79639b1..144b46d 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -86,7 +86,7 @@ int main() { #if (__cplusplus >= 201402L || (defined(_MSVC_LANG) && _MSC_VER >= 1910 && _MSVC_LANG >= 201402L)) // Compile-time supported by C++14. constexpr auto constexpr_work_fine = NAMEOF(somevar); - static_assert(constexpr_work_fine == "somevar", ""); + static_assert("somevar" == constexpr_work_fine, ""); #endif // Enum name. diff --git a/include/nameof.hpp b/include/nameof.hpp index 1015390..dd80fbf 100644 --- a/include/nameof.hpp +++ b/include/nameof.hpp @@ -60,18 +60,26 @@ template using Decay = std::remove_reference::type>::type>; inline constexpr bool StrEquals(const char* lhs, const char* rhs, std::size_t size) { - return size == 0 ? (lhs[0] == rhs[0]) : ((lhs[size - 1] == rhs[size - 1]) && StrEquals(lhs, rhs, size - 1)); + return (size == 0) ? (lhs[0] == rhs[0]) : ((lhs[size - 1] == rhs[size - 1]) && StrEquals(lhs, rhs, size - 1)); } -// STD like compile-time string. +inline constexpr std::size_t StrLen(const char* str, std::size_t size = 0) { + return (str == nullptr) ? 0 : ((str[size] == '\0') ? size : StrLen(str, size + 1)); +} + +// STD like compile-time const char* string. class cstring final { const char* str_; std::size_t size_; public: - constexpr cstring(const char* str, std::size_t size) noexcept : str_(str), size_(size) {} + constexpr cstring(const char* str, std::size_t length, std::size_t prefix = 0, std::size_t suffix = 0) noexcept + : str_{str + prefix}, + size_(length - prefix - suffix) {} - cstring() noexcept : str_(nullptr), size_(0) {} + constexpr cstring() noexcept : cstring{nullptr, 0, 0, 0} {} + + constexpr cstring(const char* str) noexcept : cstring{str, StrLen(str), 0, 0} {} cstring(const cstring&) = default; @@ -125,16 +133,6 @@ class cstring final { return !(lhs == rhs); } - template - inline friend constexpr bool operator==(const cstring& lhs, const char(&str)[N]) noexcept { - return (lhs.size_ == N - 1) && StrEquals(lhs.begin(), str, lhs.size()); - } - - template - inline friend constexpr bool operator!=(const cstring& lhs, const char(&str)[N]) noexcept { - return !(lhs == str); - } - inline friend std::ostream& operator<<(std::ostream& os, const cstring& str) { os.write(str.begin(), str.size()); return os;