C++ 在编译时将mpl::vector_c复制到静态数组

C++ 在编译时将mpl::vector_c复制到静态数组,c++,templates,boost,c++11,boost-mpl,C++,Templates,Boost,C++11,Boost Mpl,在C++11中,我有类似 #include <boost/mpl/vector_c.hpp> #include <boost/mpl/size.hpp> #include <boost/array.hpp> #include <iostream> namespace mpl = boost::mpl; template<std::size_t ... Args> struct Test { typedef

在C++11中,我有类似

#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/size.hpp>

#include <boost/array.hpp>

#include <iostream>

namespace mpl = boost::mpl;

template<std::size_t ... Args>
struct Test
{
            typedef mpl::vector_c<std::size_t, Args ...> values_type;

            static const boost::array<std::size_t, sizeof...(Args)> values;
};


int main (int argc, char** argv)
{
            Test<3,2,5,6,7> test;
            return 0;
}
#包括
#包括
#包括
#包括
名称空间mpl=boost::mpl;
模板
结构测试
{
typedef mpl::vector_c value_type;
静态常量boost::数组值;
};
int main(int argc,字符**argv)
{
试验;
返回0;
}
我想用mpl::vector_c中的值“contained”初始化boost::array内容。此初始化应在编译时执行。我已经看到了一些使用预处理器的解决方案,但是我不知道如何将它们应用到可变模板案例中

注意,在上面的示例代码中,mpl::vector_c的元素与测试的模板参数相同。在实际代码中,情况并非如此,,而是
值\u type
的长度==模板参数的数量,但实际值是应用一系列mpl算法得到的。因此,不要假设论点是相同的


希望问题清楚,谢谢

一种方法是使用
at_c
将向量_c提取到参数包中,然后展开它并使用它初始化数组

#include <cstdio>
#include <array>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/size.hpp>
#include <utils/vtmp.hpp>
// ^ https://github.com/kennytm/utils/blob/master/vtmp.hpp

template <typename MPLVectorType>
class to_std_array
{
    typedef typename MPLVectorType::value_type element_type;
    static constexpr size_t length = boost::mpl::size<MPLVectorType>::value;
    typedef std::array<element_type, length> array_type;

    template <size_t... indices>
    static constexpr array_type
            make(const utils::vtmp::integers<indices...>&) noexcept
    {
        return array_type{{
            boost::mpl::at_c<MPLVectorType, indices>::type::value...
        }};
    }

public:
    static constexpr array_type make() noexcept
    {
        return make(utils::vtmp::iota<length>{});
    }
};
是在编译时运行的,因为
make()
函数是
constexpr



同样的技术通常用于将
std::tuple
扩展为
std::array
(),扩展为函数调用(),等等。

我只是想知道,与
相比(大小:{3,2,5,6,7})
?@betabandido:不,它们都编译到同一个程序集(当然是在优化之后)但是,我想在更复杂的模板元编程使用中,问题和您的解决方案中显示的方法实际上是必要的,对吗?例如,我认为数组需要从一个函数传递到另一个函数。在这种情况下也可以使用普通数组({3,2,…})吗?@betabando:我不明白你的问题。可以使用基于范围的
for
@CntrAltCanc:Uniform initialization对数组和初始值设定项列表进行迭代。理想情况下,一对
{
就足够了(即
数组类型{…}
),但叮当声会产生错误。
int main()
{
    typedef boost::mpl::vector_c<size_t, 3, 2, 5, 6, 7> values;

    for (size_t s : to_std_array<values>::make())
        printf("%zu\n", s);
    return 0;
}
to_std_array<MPLVector>::make()