I have a struct which wraps multiple std::sets of data. I want access to the sets to be computed at compile time. To do this, I created a template constexpr getter method to return the requested set.
// simplified sample
struct TwoSets
{
template <int i> constexpr std::set<int> &get() noexcept
{
if constexpr (i == 0) {
return first;
} else if constexpr (i == 1) {
return second;
} else {
static_assert(i == 0 || i == 1, "invalid");
}
}
std::set<int> first;
std::set<int> second;
};
This works, but there are parts of the code that insert to a given set, and parts of the code that want read-only access to a set via a const reference to the set like so:
TwoSets sets;
sets.get<0>().insert(0);
// ...elsewhere in code
const TwoSets &const_sets = sets;
std::cout << const_sets.get<0>().size();
This results in an error:
error: passing ‘const TwoSets’ as ‘this’ argument discards qualifiers [-fpermissive]
This can be fixed by marking get as const/returning a const reference, which breaks the insertion code. What do I need to do to both be able to both
- Perform the set selection at compile time
- Access the sets with a mutable reference and with a
constimmutable reference
getstd::tuplehere? e.g. godbolt.org/z/h3cP83o5dstatic_assert()can be reduced, since we knowi == 0 || i == 1is false.