0

I have encountered a template syntax that I am not able to understand :

template <typename T, typename U>
struct is_same
{
    static const bool value = false;
};

template <typename T>
struct is_same<T, T>
{
    static const bool value = true;
};

template <class A, class B>
bool IsSameClass() {
    return is_same<A, B>::value;
}

The above program implement a template boolean function IsSameClass() that return true if both the classes are of same type.

I don't understand this part :

template <typename T>
struct is_same<T, T>
{
    static const bool value = true;
};

Is it structure taking two argument ?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
user2679476
  • 365
  • 3
  • 12
  • 6
    It's a partial specialization of the overall `is_same` struct. `is_same` is a template that takes two arguments, `T` and `U`. The specialization handles the case when both arguments are the same thing, `T`. – Nathan Pierson Aug 13 '23 at 06:15
  • 3
    See [partial_specialization](https://en.cppreference.com/w/cpp/language/partial_specialization). – Jarod42 Aug 13 '23 at 07:36
  • It’s _partial specialization_, combined (in a way) with the concept of _unification_ known from functional / logical programming. When the partial specialization of `is_same` can be applied (i.e. its arguments _are_ the same type), then it takes precedence over the default (`false`) case, which resolves `value` to `true`. My concern about this specific code is that (1) such constructs may yield unexpected results without a healthy dose of `std::decay` and `std::remove_reference`, depending on context, and (2) it has quite a few missed `constexpr` opportunities. – Andrej Podzimek Aug 13 '23 at 16:30

0 Answers0