簡體   English   中英

在constexpr數據數組中存儲任意數據

[英]Storing arbitrary data in constexpr data array

我正在嘗試在編譯時創建一個跳轉表的想法,然后在運行時使用它。 它會像這樣工作:

struct blah { constexpr blah() {} int operator()() const { return 42; }};
int fun(std::string const& str)
{
    return switch_ {
        case_{ "hello"_s, [](){ return 5; }
        case_{ "blah"_s, blah{} }
    }(str);
}

在這種情況下, _sconstexpr字符串

這個想法是,這將在編譯時使用constexpr哈希函數創建一個哈希表。

我相信我已經解決了每個問題,只有一個例外,如果不能解決,可能會使這個想法無法實現。 那就是初始化。

哈希是通過數組實現的。 沖突將被放置在該數組中的空單元格中。 因此,我需要找到一種方法將所有數據類型存儲為單一類型。 基本的類型擦除技術似乎無效。 也不能使用placement new或將值轉換為字節並將它們復制到數組中。 還嘗試使用UB調用聯合技巧,該技巧通常在運行時有效,但在constexpr上下文中是不允許的。

似乎唯一可用的選項是呈現一種實際上更像是元組的各種聯合。 因此它只存儲一個值,但占用散列中所有類型的內存。 這對我來說似乎不好。

那么,誰能想到一種將任意類型存儲到constexpr生成的數組中的方法?

我認為沒有一般方法可以解決您的問題。 但是在最近的字符串文字的情況下,我提出了一種(非完美的)將它傳遞給模板類作為參數的方法,你可以在這里找到它。

使用它你可以創建一種由字符串文字索引的數組,例如通過專門化:

#include <iostream>
#include <functional>

#include "string_literal.h"

template <class SLiteral>
struct switch_;

template <>
struct switch_<STRING_LITERAL(3, "abc")> {
   int do_something() { return 1; }
};

template <>
struct switch_<STRING_LITERAL(12, "123456789012")> {
   int do_something() { return [](){ return 5;}(); }
};

template <>
struct switch_<STRING_LITERAL(8, "blahblah")> {
   std::function<int()> foo;
   template <class T>
   switch_(T t) {
      foo = t;
   }
   int do_something() { return foo(); }
};

int main() {
   std::cout << switch_<STRING_LITERAL(3, "abc")>().do_something() << std::endl;
   std::cout << switch_<STRING_LITERAL(12, "123456789012")>().do_something() << std::endl;
   std::cout << switch_<STRING_LITERAL(8, "blahblah")>([](){return 10;}).do_something() << std::endl;
}

程序的輸出為:

1
5
10

暫無
暫無

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

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