Ant*_*ier 8 c++ template-meta-programming variadic-templates constexpr c++14
我想将"数组"转换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
}
Run Code Online (Sandbox Code Playgroud)
我收到调用该computeIndices函数的行的错误.这段代码c ++ 14是否正确?是否可以这样做?我正在使用MSVC,我得到这个错误:表达式没有评估为常量
此代码看起来正确,并在编译为C++ 17时有效.它使用std::array::begin,只constexpr在C++ 17中制作.
使用clang时可以实现更好的编译错误,其中指出:
<source>:23:25: note: non-constexpr function 'begin' cannot be used in a constant expression
auto it = array.begin();
Run Code Online (Sandbox Code Playgroud)