C++ constexpr:在编译时计算 std 数组

2024-03-27

我想转换一个“数组”bool到一个整数序列。 所以我需要计算一个std::array在编译时。

这是我的代码

#include <array>

template<typename InputIt, typename T >
inline constexpr typename std::iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T &value ) {
    typename std::iterator_traits<InputIt>::difference_type ret = 0;
        for (; first != last; ++first) {
            if (*first == value) {
                ret++;
            }
        }
        return ret;
}

template<bool ..._values>
struct keep_value {
    static constexpr std::size_t numberOfValues = sizeof...(_values);
    static constexpr bool values[] = {_values...};
    static constexpr std::size_t numberToKeep = count(values, values + numberOfValues, true);

    static constexpr std::array<std::size_t, numberToKeep> computeIndices() {
        std::array<std::size_t, numberToKeep> array{};
        auto it = array.begin();
        for(std::size_t i{0}; i < numberOfValues; ++i)
            if(values[i] == true)
                *it++ = i;

        return array;
    }

    static constexpr std::array<std::size_t, numberToKeep> indices = computeIndices();

    template<typename Indices = std::make_index_sequence<numberToKeep>>
    struct as_index_sequence{};

    template<std::size_t ...Is>
    struct as_index_sequence<std::index_sequence<Is...>> : std::index_sequence<indices[Is]...>{};
};

int main() {
    keep_value<false, true, true>::template as_index_sequence<>{}; // Should return the sequence 1 2
}

我收到调用该行的错误computeIndices功能。这段代码 c++14 正确吗?是否可以采取其他措施? 我正在使用 MSVC,但收到此错误: 表达式的计算结果不是常量


此代码看起来正确并且在编译为 C++17 时可以工作。 它用std::array::begin http://en.cppreference.com/w/cpp/container/array/begin,仅已制作constexpr在 C++17 中。

当以下情况时可以实现更好的编译错误:使用铿锵声 https://godbolt.org/g/7kKoVE,其中指出:

<source>:23:25: note: non-constexpr function 'begin' cannot be used in a constant expression
    auto it = array.begin();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ constexpr:在编译时计算 std 数组 的相关文章

随机推荐