【问题标题】:Qt vs constexpr string literalQt vs constexpr 字符串文字
【发布时间】:2019-05-18 18:54:31
【问题描述】:

有没有办法在 Qt 中定义为静态 constexpr 字符串字面量成员? IE。类似于以下内容:

class X
{
   static constexpr QString tag = "mytag";
};

【问题讨论】:

  • 使用QLatin1String。

标签: c++ qt constexpr string-literals


【解决方案1】:

我按照 Jesper 在评论中的建议做了,我使用了 QLatin1String。但是我通过一个小的帮助类使用它来避免 QLatin1String 中的 strlen() 调用:

struct ConstLatin1String : public QLatin1String
{
    constexpr ConstLatin1String(const char* const s) : 
        QLatin1String(s, static_cast<int>(std::char_traits<char>::length(s))) {}
};

这允许这样做:

static constexpr ConstLatin1String mystring = "foo";

【讨论】:

  • 我认为它有内存泄漏:code.woboq.org/qt5/qtbase/src/corelib/text/… 因为 QLatin1String 没有虚拟析构函数。
  • @H.M 这里没有内存泄漏。只有在为 ConstLatin1String 实现析构函数并且仅将其视为多态(即通过指向 QLatin1String 的指针删除它)时,我们才会遇到问题。
【解决方案2】:

Silicomancer answer 启发,但与c++11 一起使用

#include <QLatin1String>

namespace detail {

// Helper function for getting compile-time string literal's length 
// Given from: https://stackoverflow.com/q/27498592/ 
// c++11 analogue of: std::char_traits<char>::length(str); from c++14
constexpr std::size_t constLength(const char* str)
{
    return ((*str) == '\0') ? 0 : constLength(str + 1) + 1;
}

} // namespace detail

// Constructs compile-time <QLatin1String> from string literal
constexpr QLatin1String make_string(const char* str)
{
    return QLatin1String(str, detail::constLength(str));
}

// Alternate implementation for string literals only, without 
// recursive function call (reduces compilation time), using 
// known in compile-time size.
template <std::size_t SIZE>
constexpr QLatin1String make_string_from_literal(const char (&str)[SIZE])
{
    return QLatin1String(str, SIZE);
}

// Example of usage:
static constexpr QLatin1String STR = make_string("hello_world");

测试

// Helper function for compile-time strings comparison
// Given from https://stackoverflow.com/a/27490954/
constexpr bool strings_equal(const char* a, const char* b) {
    return (*a == *b) && (*a == '\0' || strings_equal(a + 1, b + 1));
}

// Compile-time in-place construction check
static_assert( strings_equal(make_string("foo").data(), "foo"), "test failed");

// Compile-time constant construction check
static constexpr QLatin1String STR = make_string("bar");
static_assert( strings_equal(STR.data(), "bar"), "test failed");

灵感补充

它与compile-time hashing 完美配合,例如in that brilliant answer,它基于(thatthat

// Note: `len` must be without null-character sign
constexpr uint32_t crc32(const char* str, std::size_t len) {
    return detail::crc32(len - 1, str) ^ 0xFFFFFFFF;
}

template <std::size_t LEN>
constexpr std::uint32_t crc32(const char (&str)[LEN]) {
    return crc32(str, LEN - 1);
}

// Overload for <QLatin1String>
//   Notice that, next methods: QLatin1String::{.data(), .size()} 
//   marked as constexpr only since Qt 5.6. 
constexpr std::uint32_t crc32(const QLatin1String& str) {
    return crc32(str.data(), str.size());
}

// ------------------------------------------------------------

// Test with explicitely specified literal size
static_assert( crc32("hello world", 11) == 0xd4a1185,  "CRC32 test failed");
static_assert( crc32("foo bar",      7) == 0xbe460134, "CRC32 test failed");

// Test with implicitly calculated literal size
static_assert( crc32("hello world") == 0xd4a1185,  "CRC32 test failed");
static_assert( crc32("foo bar")     == 0xbe460134, "CRC32 test failed");

// Test with convenient overload for <QLatin1String>
static constexpr QLatin1String STR_1 = make_string("hello world");
static constexpr QLatin1String STR_2 = make_string("foo bar");
static_assert( crc32(STR_1) == 0xd4a1185,  "CRC32 test failed");
static_assert( crc32(STR_2) == 0xbe460134, "CRC32 test failed");

这允许通过 switch-case 进行编译时字符串匹配。 switch 的两种情况都是相等的,并且在编译时计算:)

    1. 在编译时构造的字符串,允许在任何情况下使用它,并在需要的地方计算哈希。
    1. 从字符串预先计算的哈希值。字符串不存在。
    1. 无需任何仪式就地使用:D
static constexpr QLatin1String MATCH_1 = make_string("value_1"); // 1)
static constexpr auto MATCH_2 = crc32( make_string("value_2") ); // 2)

const QLatin1String str = /* ... */;
switch( crc32(str) )
{
    case crc32(MATCH_1):   { do_something_for_value_1(); } break; // 1)
    case MATCH_2:          { do_something_for_value_2(); } break; // 2)
    case crc32("value_3"): { do_something_for_value_3(); } break; // 3)
}

【讨论】:

    【解决方案3】:

    考虑到QString 是一个(可能)堆分配的字符串,你不能在constexpr 代码中分配内存,不。它在编译时并不比使用 std::string 更有效。

    【讨论】:

    • QStringLiteral 宏创建一个“QString 文字”。如果可以是 constexpr 那就太好了,因为它不会按照我的理解进行堆分配。
    • 从 C++20 开始,可以在 constexpr 上下文中分配内存和使用 std::string
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 2012-11-04
    • 1970-01-01
    • 2013-05-05
    • 2011-07-02
    • 2011-07-17
    相关资源
    最近更新 更多