什么是C ++ 17中的constexpr容器?

InF*_*s X 4 c++ templates constexpr

我想创建一个类,其方法类似于std::map,但应在编译时进行排序。哪些constexpr容器适合存储键template<class K>和值template<class V>

std :: vector不满足这些要求。

UPD:我们发现std::array有很多constexpr方法。这足以解决我的问题std::array<std::pair<K, V> >。但是问题仍然存在。

Öö *_*iib 6

大多数C ++标准库容器都不能用作constexpr。AFAIK std::bitsetstd::array(任意长度)的前64位是可填充的编译时间。

在程序本身准备就绪之前,不要专注于这种性能优化。std::array在C ++ 11中,使用可变参数模板函数填充大量的编译时间并不难。

如何使用可变参数模板填充4个int数组的示例(每个int表示6种颜色之一):

constexpr int ColorCount = 6;
constexpr int PositionCount = 4;

using Positions = std::array<int, PositionCount>;

template <int N>
struct PositionsFiller
{
    template <typename T, typename ...Tn>
    static constexpr Positions fill(T packed, Tn ...rest)
    {
        return PositionsFiller<N - 1>::fill(packed / ColorCount, packed % ColorCount, rest...);
    }
};

template <>
struct PositionsFiller<1>
{
    template <typename T, typename ...Tn>
    static constexpr Positions fill(T last, Tn ...rest)
    {
        return Positions{last, rest...};
    }
};

constexpr Positions pos666(PositionsFiller<PositionCount>::fill(666));
Run Code Online (Sandbox Code Playgroud)

在C ++ 17中,由于放宽了constexpr的要求,并且不需要可变参数模板,因此可以通过简单的循环来完成:

constexpr int ColorCount = 6;
constexpr int PositionCount = 4;

using Positions = std::array<int, PositionCount>;

static constexpr Positions fillPositions(int packed)
{
    Positions ret{};
    for (Positions::size_type i = ret.size(); i > 0; --i)
    {
        ret[i-1] = packed % ColorCount;
        packed /= ColorCount;
    }
    return ret;
}

constexpr Positions pos666(fillPositions(666));
Run Code Online (Sandbox Code Playgroud)

请注意,执行复杂的准备工作会缩短编译时间。当模块仍在开发中时,这可能很烦人。更好的办法是在程序开始时填充通常的可变数组,然后再用诸如编译时填充之类的优化替换它。