【发布时间】:2018-08-12 07:49:44
【问题描述】:
我想将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,但出现此错误:
表达式未计算为常量
【问题讨论】:
-
Clang 在使用 c++14 时似乎给出了同样的错误,但是,编译是使用 c++17
-
嗯,可能函数不是 C++14 中的 constexpr,而是 C++17 中的。与 std::count 相同,在 C++20 中将是 constexpr
-
确实,看我的回答
标签: c++ c++14 variadic-templates template-meta-programming constexpr