Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL type_traits question

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.

like image 368
Kim Sun-wu Avatar asked Dec 30 '10 07:12

Kim Sun-wu


People also ask

What is the default class for character traits in C++?

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:

What is STL in C++?

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.

What are the components of STL?

Other STL components include function objects (objects of a class that defines operator ()), or allocators (which manage memory allocation and deal location for containers).

What is a basic trait for types?

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)


1 Answers

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.

like image 130
maxim1000 Avatar answered Sep 30 '22 02:09

maxim1000