Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++14 using alias for is_same::value

This question uses is_same<uint64_t, decltype(val)>::value.

I expected there to be a C++14 using alias: is_same_v similar to the helper types: conditional_t, enable_if_t, and tuple_element_t which I use in my answer. Because the only thing I ever use any of those functions for is to get the type. So the *_t helper just makes sense.

Which brings me to my question, why is there no using alias is_same_v in C++14? The only thing I use is_same for is it's value. Perhaps the usage of is_same is not typically for template declarations?

like image 416
Jonathan Mee Avatar asked Mar 09 '15 12:03

Jonathan Mee


2 Answers

is_same_v (and other *_v type traits) have been proposed by N3854. They didn't make into C++14 but they are in the Library Fundamentals TS.

One of the concerns was a potential overlap with the Concepts Proposal which might offer a better alternative for type traits (and many other current meta-programming techniques). An outdated but clearer explanation of Concepts can be found here.

like image 65
Cassio Neri Avatar answered Oct 17 '22 00:10

Cassio Neri


Introduction

The primary reason for introducing std::enable_if_t<cond, T> as a shorter form ofstd::enable_if<cond, T>::type is not to shave of a mere count of 4 characters.

Since std::enable_if, and other type-traits of its kind, is mostly used in dependent contexts, it is quite painful having to write (A) when (B) would suffice:

Example

template<class T, class = typename std::enable_if<cond, T>::type> // (A)
struct A;

template<class T, class = std::enable_if_t<cond, T>>              // (B)
struct A;


Dependent Names

We need typename prior to std::enable_if because ::type is a dependent-name, and without it the Standard says that the expression shall be parsed as if ::type is actually a value.

std::is_same<T, U>::value is really a value, so there's no need for the use of typename; which in turns mean that we are effectively shaving of a mere count of 4 characters.. nothing more.


Further Reading

  • stackoverflow.com - Where and why do I have to put the template and typename keywords?


So, why isn't there a variable-template for std::is_same?

Simply because there isn't that big of a need, so no one did propose the addition in time; as most are satisfied with the below alternatives:

std::is_same<T, U> {} == std::is_same<T, U>::value
std::is_same<T, U> () == std::is_same<T, U>::value

Further Reading

There is a proposal, written by Stephan T. Lavavej, to add variable-templates for the suitable type-traits.

  • open-std.org - N3854 - Variable Templates For Type Traits
like image 8
Filip Roséen - refp Avatar answered Oct 16 '22 22:10

Filip Roséen - refp