Ankit Acharya
Ankit Acharya

Reputation: 3111

Why type_traits are classes & not functions

I have been looking into type_traits recently & was wondering why are they implemented as class templates whereas implementing them as functions could be more obvious & have a simpler syntax.

What I want to say is this syntax :-

int x = 5;
std::cout << is_same<int>(x);

Is more convincing & cleaner than the actual one ie :-

int x = 5;
std::cout << is_same <int, decltype(x)>::value;

This is just a case of curiosity. I just want to know the philosophy of the Standardization Committee in preferring the class method over the function method.

Upvotes: 3

Views: 232

Answers (1)

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

  1. Versality. Most type traits have both X::value boolean constant and X::type type alias which can be used for tag dispatch.
  2. Ability to partially specialize. You cannot have partial specialization for function, only full specializations and overloads. It is easy to call wrong function in presence of both specializations and overloads.
  3. Compile-time evaluation. Most of type traits were invented in previous millenia, when constexpr functions were not avaliable. Even in constexpr functions you cannot pass values as parameter, as it might prevent compile-time evaluation.
  4. You always have type, but sometimes it is all you have. Creating a function which does not work all the time is counterproductive, so we will not be able to rely on template parameter deduction anyway.

Upvotes: 8

Related Questions