0

Can C++20 concepts be used instead of templates to avoid (const/not const) code duplication ? For example (Range has nothing to do with C++20 ranges in this example), twice the same code, one const, the other not:

I know there is the possibility to use const_cast, but I was wondering if there might be a better way using C++20 concepts ?

template <typename Pr>
vector<span<Range> > chunk_by(vector<Range>& path, const Pr& InSameChunk)
{
    vector<span<Range> > chunks;

    int i_prev=0;
    for (int i=1;i < path.size(); i++)
    {
        if (!InSameChunk(path[i-1], path[i]))
        {
            span<Range> chunk(&path[i_prev], i - i_prev);
            chunks.push_back(chunk);
            i_prev=i ;
        }
    }
    span<Range> chunk(&path[i_prev], path.size() - i_prev);
    chunks.push_back(chunk);

    return chunks;
}

template <typename Pr>
vector<span<Range const> > chunk_by(const vector<Range>& path, const Pr& InSameChunk)
{
        vector<span<Range const> > chunks;

        int i_prev=0;
        for (int i=1;i < path.size(); i++)
        {
                if (!InSameChunk(path[i-1], path[i]))
                {
                        span<Range const> chunk(&path[i_prev], i - i_prev);
                        chunks.push_back(chunk);
                        i_prev=i ;
                }
        }
        span<Range const> chunk(&path[i_prev], path.size() - i_prev);
        chunks.push_back(chunk);

        return chunks;
}
Ludovic Aubert
  • 9,534
  • 4
  • 16
  • 28
  • Yes, because I use the result of the non const version to update the input – Ludovic Aubert Feb 16 '22 at 16:19
  • 1
    Broadly speaking, concepts aren't useful without templates. I mean, that's what they're for; they constrain templates. So I'm not sure how concepts would ever help in this situation. – Nicol Bolas Feb 16 '22 at 16:19
  • 1
    You could always solve this with templates. I don't think constraints make anything possible that wasn't previously impossible regarding this problem. – François Andrieux Feb 16 '22 at 16:27
  • 1
    I thought this is going to be a question about const and non-const member function duplication. However in this case duplication can be eliminated with `std::is_const` and `std::conditional` from C++11. You just need to apply `const` from vector into `Range`. I should also mention that creating a temporary object at `span chunk(&path[i_prev], i - i_prev); chunks.push_back(chunk);` is also unnecessary and can be simplified to `chunks.emplace_back(&path[i_prev], i - i_prev);` – user7860670 Feb 16 '22 at 16:32

0 Answers0