Search code examples
c++c++17type-traits

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?


Solution

  • 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.