smoes
smoes

Reputation: 601

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

I am currently looking for a data-structure that encapsulates data for compile-time access. Thereby, the accessed values should returned as constexpr.

While a tuple does have a constexpr constructor, the get function of the tuple does not return a constexpr.

Does such a data structure exist or is it possible to manually define such a data structure?

The final goal is to pack compile time known values within some kind of object, pass it (via template) to a function, access the elements there and have the compile time known values directly pasted inplace in the binary as constants. For my purpose the encapsulation part is crucial.

Upvotes: 4

Views: 235

Answers (1)

TemplateRex
TemplateRex

Reputation: 70546

As of C++14, std::tuple does accept a constexpr std::get

#include <tuple>

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

Live Example

Similarly, you can use std::array as well with std::get (and also the operator[] is now constexpr). Raw C-arrays can also be done.

#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, "");
}

Live Example

Upvotes: 1

Related Questions