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?
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:
rightfold's answer on that first one gives a superb example of when traits are useful:
For example, an implementation of
std::copy
may usestd::memcpy
internally instead of an explicit loop when the iterators are pointers to PODs. This can be achieved with SFINAE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With