Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between using std::is_same<T,U>::value and std::is_same_v<T,U> in any scenario?

Are there any situations in which they act differently? I am using them with constexpr.

template<typename T>
T* getptr(){ 
    if constexpr (std::is_same<T,int>::value) { return someptr;}
}

I did not find any differences when searching, and compiling and running the code always gives the same result.

I am curious if there's any way they act differently, which is not trivial?

like image 754
Illuminati Avatar asked Dec 10 '25 23:12

Illuminati


1 Answers

As you can see in the documentation std::is_same_v is defined as:

template< class T, class U >
constexpr bool is_same_v = is_same<T, U>::value;

So for all practical purposes there should be no difference between the effect of using is_same<T,U>::value and is_same_v<T,U>.

is_same_v is given as a convenience API (a "Helper variable template") to enable you to write code which is more succinct.

However an important difference is that is_same_v is available only from C++17, so if you'll compile your code with an older version you will have to resort to is_same<>::value (available from C++11).

Some more esoteric differences are given in the comments above (since you asked for any difference):

  1. As StoryTeller - Unslander Monica commented, you can encounter a SFINAE ralated difference - see this post for more info.
  2. As Eljay commented if the program adds specializations for std::is_same or std::is_same_v, the behavior is undefined. So in principle there could be a difference if your program add a specialization (which it shouldn't anyway).

A side note:
The above is valid in general for all the _v and _t APIs for the standard type-traits.

like image 75
wohlstad Avatar answered Dec 13 '25 14:12

wohlstad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!