簡體   English   中英

C++20 字符串文字模板參數工作示例

[英]C++20 string literal template argument working example

有人可以將 C++20 的特征字符串模板的最小可復制示例發布為模板參數嗎?

這個來自ModernCpp的不編譯:

template<std::basic_fixed_string T>
class Foo {
    static constexpr char const* Name = T;
public:
    void hello() const;
};

int main() {
    Foo<"Hello!"> foo;
    foo.hello();
}

我已經設法根據這個 Reddit 帖子編寫了一個可行的解決方案:

#include <iostream>

template<unsigned N>
struct FixedString 
{
    char buf[N + 1]{};
    constexpr FixedString(char const* s) 
    {
        for (unsigned i = 0; i != N; ++i) buf[i] = s[i];
    }
    constexpr operator char const*() const { return buf; }

    // not mandatory anymore
    auto operator<=>(const FixedString&) const = default;
};
template<unsigned N> FixedString(char const (&)[N]) -> FixedString<N - 1>;

template<FixedString Name>
class Foo 
{
public:
    auto hello() const { return Name; }
};

int main() 
{
    Foo<"Hello!"> foo;
    std::cout << foo.hello() << std::endl;
}

現場演示

但確實為固定字符串提供了自定義實現。 那么現在最先進的實現應該是什么?

P0259 fixed_string已經退役,因為它的大多數用例都可以通過P0784 更好地實現更多 constexpr 容器(又名 constexpr 析構函數和瞬態分配) - 即能夠在 constexpr 上下文中使用std::string本身。

當然,即使您可以在 constexpr 中使用std::string ,也不能將其用作 NTTP,但看起來我們不會很快將結構字符串 class 納入標准。 我建議現在使用您自己的結構字符串 class ,准備好將其別名為適當的第三方 class 以應對流行庫中出現的問題,或者在發生這種情況時使用標准字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM