簡體   English   中英

通過 C++ 中的 function 參數進行模板實例化?

[英]template instantiation via a function parameter in C++?

我有一個 class 模板,它將編譯時字符串作為模板參數。 例如


template<size_t Size>
struct Buffer
{
    char buffer[Size] = {0};
    consteval Buffer(const char (&arr) [ Size ])
    {
        for(size_t i = 0; i != Size; ++i) buffer[i] = arr[i]; 
    }

};
// this is the template which I want to instantiate with a function parameter
template<Buffer buffer>
struct interned_buffer
{
    consteval static const char* first() { return &buffer.first; }
};

constexpr const char* example = "hello";

struct MyStruct
{
    template<size_t Size>
    consteval MyStruct(const char (&arr) [ Size ] ) requires(std::is_constant_evaluated())
    {
        if constexpr(5 > Size)
            first = example;
        else
            first = interned_buffer<arr>::first();
            // error 'arr' is not a constant expression :(
    }
private:
    const char* first = nullptr;
};

constexpr static MyStruct s = "hello";

這當然不是真實世界的代碼,這是一個小例子(真實代碼要復雜得多且無關緊要)。 TLDR:我想從編譯時已知的 FUNCTION 參數實例化一個模板。

如果唯一的問題是 arr 不是 constexpr,通過模板傳遞它

因為,構造函數不能用菱形括號調用,你需要創建一些包裝器並將其派發到那里,就像這樣

template <auto buffer>
struct bufferHolder
{
    constexpr static auto buf = buffer;
};

struct MyStruct
{
    template<auto buffer>
    consteval MyStruct(bufferHolder<buffer>)
    {
        if constexpr(5 > std::size(buffer.buffer))
            first = example;
        else
            first = interned_buffer<buffer>::first();
    }
private:
    const char* first = nullptr;
};

constexpr static MyStruct s = bufferHolder<Buffer{"hello"}>{};

暫無
暫無

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

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