c++ - 具有成员变量的 Const 对象数组 = 先前索引成员变量的总和

标签 c++ arrays c++11 constexpr compile-time

是否可以创建一个常量对象数组,其中一个成员变量是在它之前创建的对象中的成员变量的总和?

class Data
{
public:
    constexpr Data(uint32_t offset, uint32_t length) :
        m_offset(offset), m_length(length)
    {
    }

    uint32_t m_offset; //would like this to be calculated at compile time
    uint32_t m_length;
};

const Data dataList[] =
{
    Data(0, 10),
    Data(10, 25),
    Data(35, 20)
};

偏移量是数组中所有先前对象的长度之和(索引 2 中的 10 + 25 = 35)。

我想避免手动计算偏移量。

我尝试过 std::integral_constant 和对 constexpr 的递归调用,但似乎没有什么可以分享的工作解决方案。非常感谢任何指导!

最佳答案

如果您接受基于 std::array<Data, ...> 的答案而不是旧的 C 风格数组,使用 C++14 而不是 C++11,这很容易

下面是一个完整的例子

#include <array>
#include <iostream>

struct Data
{
   constexpr Data(uint32_t offset, uint32_t length) :
      m_offset(offset), m_length(length)
    { }

    uint32_t m_offset;
    uint32_t m_length;
};

template <uint32_t ... Ls>
constexpr std::array<Data, sizeof...(Ls)> getDataList ()
 {
   uint32_t  l0 { 0U };
   uint32_t  l1 { 0U };

   return { { (l0 = l1, l1 += Ls, Data(l0, l1))... } };
 }

int main ()
 {
   constexpr auto dl = getDataList<10U, 25U, 20U>();

   for ( auto const & d : dl )
      std::cout << " - " << d.m_offset << ", " << d.m_length << std::endl;
 }

-- 编辑 --

OP 无法使用 std::array但是 C++ 函数不能返回 C 风格的数组;一个解决方案可以模拟 std::array 的(iper 简化)版本, 将 C 风格的数组包装在一个简单的结构中

template <typename T, std::size_t N>
struct myArray
 { T arr[N]; };

现在完整的例子变成了

#include <array>
#include <iostream>

template <typename T, std::size_t N>
struct myArray
 { T arr[N]; };

struct Data
{
   constexpr Data(uint32_t offset, uint32_t length) :
      m_offset(offset), m_length(length)
    { }

    uint32_t m_offset;
    uint32_t m_length;
};

template <uint32_t ... Ls>
constexpr myArray<Data, sizeof...(Ls)> getDataList ()
 {
   uint32_t  l0 { 0 };
   uint32_t  l1 { 0 };

   return { { (l0 = l1, l1 += Ls, Data(l0, l1))... } };
 }

int main ()
 {
   constexpr auto dl = getDataList<10U, 25U, 20U>();

   for ( auto ui = 0U ; ui < 3U ; ++ui )
      std::cout << " - " << dl.arr[ui].m_offset << ", "
         << dl.arr[ui].m_length << std::endl;
 }

std::array模拟可以稍微简单一些,例如包含一个 static constexpr具有维度的成员

template <typename T, std::size_t N>
struct myArray
 { static constexpr std::size_t dim { N }; T arr[dim]; };

所以 main() 中的循环可以用吗

// ..........................vvv
for ( auto ui = 0U ; ui < dl.dim ; ++ui )

关于c++ - 具有成员变量的 Const 对象数组 = 先前索引成员变量的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46548329/

相关文章:

c++ - LLVM 是避免动态转换规则的异常(exception)吗?

java - 返回一个空数组

c++ - result_of<F(Args...> 和 decltype<f(args...)> 有什么区别?

Java:对数组列表进行排序并以二维数组形式返回

c++ - 如果我将它绑定(bind)到 "this", std::bind 是否保留对象的引用/拷贝?

c++ - 如何安全地终止线程? (使用指针)c++

c++ - 在另一个方法完成后立即调用一个方法

c++ - 在动态加载的 dll 中查找名称错误的函数

c++ - 如何在不使用 make 文件的情况下运行 C 代理示例程序?

arrays - Swift HTTP POST 二维数组