Define same class with diff. concepts using concepts

I want to create a template class, RRR, that can accept both reference and non-reference types, as shown below:

    template <typename T> requires (std::is_reference_v<T>)
    struct RRR
    {
        T m_value{};
        RRR(T init) : m_value{ init }
        {}
    };

    template <typename T> requires (!std::is_reference_v<T>)
    struct RRR
    {
        T m_value{};
        RRR(T init) : m_value{ init }
        {}
    };

However, I am facing a compile error when I use the template:

error: redeclaration ‘template requires is\_reference\_v struct RRR’ with different constraints

What is the solution for defining a template like this?

The issue you are facing is due to redeclaration of the template class RRR with different constraints. The solution is to use a single template definition with a combination of type traits to handle both reference and non-reference types.

Here’s the updated code:

template <typename T>
struct RRR
{
    T m_value{};
    RRR(T init) : m_value{ init }
    {}
};

template <typename T>
struct RRR<T&>
{
    T& m_value;
    RRR(T& init) : m_value{ init }
    {}
};

In this updated code, the first template definition handles non-reference types, and the second template definition handles reference types. By specializing the second template for T&, we can handle reference types separately.

Now you can use the RRR class with both reference and non-reference types without any compile errors.