C++ type trait that returns a type telling whether two types are the same or not

105 Views Asked by At

std::is_same_v allows to know whether two types are the same or not; one gets a constant boolean value that holds this information.

Question: is there something in std that allows to get a type (either std::true_type or std::false_type) instead of a const value that holds this information ?

Actually, I wrote the following is_same_t that seems to do the job but I wonder if I am not reinventing (possibly wrongly) the wheel.

#include <type_traits>

template<typename A, typename B>
using is_same_t = std::conditional_t <std::is_same_v <A,B>, std::true_type, std::false_type>;

static_assert (std::is_same_v<is_same_t<int,int>,  std::true_type>);
static_assert (std::is_same_v<is_same_t<int,char>, std::false_type>);

int main () {}
1

There are 1 best solutions below

3
Jeff Garrett On

std::is_same<A, B> itself gives you types publicly and unambiguously derived from std::true_type and std::false_type.

Remove the _v.

See https://en.cppreference.com/w/cpp/types/is_same