Adam Hunyadi Adam Hunyadi - 2 months ago 19
C++ Question

Binding const references to const values only

I am working on a code that finds pairs (using a specific condition) among the elements of a collection. I don't really want to duplicate the elements of the collection, so I figured I would use pointer pairs. This however is unsafe if the values in the original collection can change.

In my code I would like to use a const reference that only binds to truly constant values (because I don't want to let the users to abuse the pairs). This approach however:

using PairCollectionType =
std::vector<std::pair<std::shared_ptr<Cluster>, std::shared_ptr<Cluster>>>;

PairCollectionType getClusterPairCollection(
const std::vector<Cluster> const& clusterCollection)
// ...

-> results an error of "duplicate 'const'". I know that this is possible with pointers:

const ptr_type* const ptrThatBindsOnlyToConsts;

Is this somehow possible with references too?


I'm not sure about your rationale for needing to do this. But you can give a compilation error if the caller passes a non-const argument, by adding overloads to catch those cases:

void func(U const &)
    // the real code

void func(U &) = delete;
void func(U&&) = delete;

int main()
    U u;
    U const cu {};

    func(cu);    // OK
    func(u);     // error
    func(U{});   // error