簡體   English   中英

帶get的數據結構,返回constexpr(C ++)

[英]Data structure with get, returning a constexpr (C++)

我目前正在尋找一種封裝數據的數據結構,以便進行編譯時訪問。 因此,訪問的值應作為constexpr返回。

雖然元組確實有一個constexpr構造函數,但元組的get函數不會返回constexpr。

是否存在這樣的數據結構,或者是否可以手動定義這樣的數據結構?

最終目標是在某種對象中打包編譯時已知值,將其(通過模板)傳遞給函數,訪問那里的元素,並將編譯時已知值直接粘貼到二進制文件中作為常量。 為了我的目的,封裝部分至關重要。

從C ++ 14開始, std::tuple確實接受了constexpr std::get

#include <tuple>

int main()
{
   constexpr std::tuple<int, int, int> t { 1, 2, 3 };
   static_assert(std::get<0>(t) == 1, "");
}

實例

類似地,你可以使用std::array以及std::get (而且operator[]現在也是constexpr )。 原始C陣列也可以完成。

#include <array>

int main()
{
   constexpr std::array<int, 3> a {{ 1, 2, 3 }};
   static_assert(std::get<0>(a) == 1, "");
   static_assert(a[0] == 1, "");
}

實例

暫無
暫無

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

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