Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::is_same and std::is_same_v — type identity

std::is_same and std::is_same_v from <type_traits> check at compile time whether two types are exactly the same type. They account for const, volatile, and references; they do not test value equality or convertibility.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <type_traits>
std::is_same<T, U>::value
std::is_same_v<T, U>

std::is_same<T, U> from <type_traits> is a class template that checks type identity at compile time. It derives from std::true_type when T and U denote exactly the same type with the same const and volatile qualifications; otherwise, it derives from std::false_type.

std::is_same<T, U>::value exposes the result as a Boolean constant. std::is_same_v<T, U> is a variable template providing a shorter spelling of that same result, not a type or a function call. Either spelling can be used in static_assert to enforce a type requirement at compile time.

The comparison does not remove qualifications or references: int, const int, volatile int, int&, and int&& are different types. An alias such as using Count = int; does not create a new type, so comparing Count with int yields true.

Do not confuse type identity with value equality or convertibility: comparing int with double yields false. The example checks these distinctions using static_assert; its empty main prints no text.

Examples

#include <type_traits>

using Count = int;

static_assert(std::is_same<Count, int>::value);
static_assert(std::is_same_v<Count, int>);
static_assert(!std::is_same_v<int, const int>);
static_assert(!std::is_same_v<int, volatile int>);
static_assert(!std::is_same_v<int, int&>);
static_assert(!std::is_same_v<int&, int&&>);
static_assert(!std::is_same_v<int, double>);

int main() {}

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources