【问题标题】:Data structure with get, returning a constexpr (C++)带有 get 的数据结构,返回一个 constexpr (C++)
【发布时间】:2015-08-20 12:10:36
【问题描述】:

我目前正在寻找一种封装数据以供编译时访问的数据结构。因此,访问的值应该返回为 constexpr。

虽然元组确实有 constexpr 构造函数,但元组的 get 函数不返回 constexpr。

这样的数据结构是否存在或者是否可以手动定义这样的数据结构?

最终目标是将编译时间已知值打包到某种对象中,将其(通过模板)传递给函数,访问那里的元素,并将编译时间已知值作为常量直接粘贴到二进制文件中。就我而言,封装部分至关重要。

【问题讨论】:

  • std::initializer_list?
  • 在上面的示例中使用std:array,对结构中数组的访问被编译为callq std::array<int, 2ul>::operator[](unsigned long) const,这根本不是常量,而是我假设的内存访问......跨度>
  • 明确一点:它可能是常量,但它不是存储在数组中的整数常量,就像我想要的那样!

标签: c++ arrays tuples c++14 constexpr


【解决方案1】:

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

Live Example

同样,您也可以将std::arraystd::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, "");
}

Live Example

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 2022-07-10
    • 2015-12-24
    相关资源
    最近更新 更多