2

I want to create template class to get reference type and non-reference type template class with same class like 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 }
        {}
    };

but when I use this, I met below compile error.

error: redeclaration ‘template requires is_reference_v struct RRR’ with different constraints

what is solution for defining template like this case?

yi bruce
  • 71
  • 4

1 Answers1

6

Make them partial specializations:

    template <typename T>
    struct RRR;

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

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

You can even have one of them be a partial specialization and the other the primary template:

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

    // This one will be used for references since it is more constrained
    template <typename T> requires (std::is_reference_v<T>)
    struct RRR<T>
    {
        T m_value{};
        RRR(T init) : m_value{ init }
        {}
    };

Artyer
  • 31,034
  • 3
  • 47
  • 75
  • 3
    @yibruce: If this answers your question, you can choose to accept it (the green checkmark). – nick Jun 23 '23 at 05:27