The following code compiles in Clang and GCC, but fails in MSVC.
template <typename... FieldsSequence>
struct S {
static constexpr bool checkIdUniqueness()
{
using IdType = int;
constexpr IdType fieldIds[sizeof...(FieldsSequence)]{ 0 };
for (size_t i = 0; i < std::size(fieldIds) - 1; ++i)
{
if (fieldIds[i] > fieldIds[i + 1])
{
constexpr auto tmp = fieldIds[i];
fieldIds[i] = fieldIds[i + 1];
fieldIds[i + 1] = tmp;
}
}
return true;
}
};
The error message is:
expression did not evaluate to a constant
note: failure was caused by a read of a variable outside its lifetime
note: see usage of 'i'
Is there a way to make this work with all the three compilers? Ultimately, I need to bubble-sort the array to assert at compile time that all the values are unique.
FieldsSequence?std::sort? And regarding the uniqueness, can't you use sets?std::sortis notconstexpruntil C++20, andstd::setnot even then (AFAIK). If my code will work, I don't see why a second inner loop won't. Resulting in compile-time bubble-sorting. And then a separate for loop to check for uniqueness.