Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point in knowing whether an object is an integral or not or is a class type or not?

Tags:

c++

templates

Hello I've seen many examples like this in Cppreference.com:

std::is_class<T>
std::is_integral

And so on. I know if I run the code for example I get true or false. But what is the point in that? e.g knowing the object is of class type or not?

#include <iostream>
#include <type_traits>

struct A {};
class B {};
enum class C {};

int main()
{
    std::cout << std::boolalpha;
    std::cout << std::is_class<A>::value << '\n';
    std::cout << std::is_class<B>::value << '\n';
    std::cout << std::is_class<C>::value << '\n';
    std::cout << std::is_class<int>::value << '\n';
}

The output:

true
true
false
false
  • I've searched all over for a real example using this (is_class, is_integral, is_arithmetic, ...) But all the tutorials show only the hopeless example: only true or false.

  • Could anyone help me with a small useful example using this templates?

like image 967
Rami Yen Avatar asked Nov 06 '19 17:11

Rami Yen


1 Answers

It's not for writing to the console, that's for sure.

More broadly you're asking: what is the point of type traits?

The answer is template metaprogramming. For example, I can create a template specialisation that does one thing for integral types, and another for non-integral types.

Aaron Bullman has a simple introduction to type traits, as does Jacek here.

In my opinion, most use of these things will be found buried within implementations of cool features and classes and utilities (i.e. in libraries) as part of the background machinery that makes it all work.

Further reading:

  • C++ Type Traits
  • How do traits classes work and what do they do?

rightfold's answer on that first one gives a superb example of when traits are useful:

For example, an implementation of std::copy may use std::memcpy internally instead of an explicit loop when the iterators are pointers to PODs. This can be achieved with SFINAE.

like image 99
Lightness Races in Orbit Avatar answered Oct 23 '22 14:10

Lightness Races in Orbit