I was watching the latest C9 lecture and noticed something interesting..
In his introduction to type_traits, Stephan uses the following (as he says, contrived) example:
template <typename T>
void foo(T t, true_type)
{
std::cout << t << " is integral";
}
template <typename T>
void foo(T t, false_type)
{
std::cout << t << " is not integral";
}
template <typename T>
void bar(T t)
{
foo(t, typename is_integral<T>::type()
);
}
This seems to be far more complicated than:
template <typename T>
void foo(T t)
{
if(std::is_integral<T>::value
)
std::cout << "integral";
else
std::cout << "not integral";
}
Is there something wrong with the latter way of doing it? Is his way better? Why?
Thanks.
To begin with, the default character traits class, char_traits<T>, is used extensively in the C++ standard. For example, there is no class called std::string. Rather, there's a class template std::basic_string that looks like this:
The STL exemplifies generic programming rather than object-oriented programming, and derives its power and flexibility from the use of templates, rather than inheritance and polymorphism. It also avoids new and delete for memory management in favor of allocators for storage allocation and deal location.
Other STL components include function objects (objects of a class that defines operator ()), or allocators (which manage memory allocation and deal location for containers).
A basic trait for types is the categories in which they can be classified. This is a chart on how these categories overlap: Is copy assignable throwing no exceptions (class template) Is copy constructible throwing no exceptions (class template) Is default constructible throwing no exceptions (class template)
Basically first option uses knowledge about "integrality" of the type at compile-time and the second option - moves this knowledge to run-time.
This means that we may use for integral types code which is not compilable for non-integral types.
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