WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Expert · question 72 of 100

What is the concept of type traits in C++, and how can they be used to enhance template programming?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

In C++, type traits refer to a set of template classes that provide information about types at compile-time. They can be used to help programmers write more generic and reusable code by providing information about the properties of a given type without having to rely on runtime information.

Type traits are typically implemented as template classes that have a static constant value or type member that represents some property of a given type. For example, the std::is_integral type trait class can be used to check if a given type is an integral type (i.e., bool, char, int, long, etc.). The std::is_integral class has a static constant value member called value that is true if the given type is integral, and false otherwise.

Here is an example of using the std::is_integral type trait to create a template function that prints out the binary representation of a given integral type:

    #include <iostream>
    #include <type_traits>
    
    template <typename T>
    typename std::enable_if<std::is_integral<T>::value>::type
    print_binary(T value)
    {
        for (int i = sizeof(T) * 8 - 1; i >= 0; i--)
        {
            std::cout << ((value >> i) & 1);
        }
        std::cout << std::endl;
    }
    
    int main()
    {
        int i = 42;
        print_binary(i);  // prints "00000000000000000000000000101010"
        
        double d = 3.14;
        print_binary(d);  // compile-time error: double is not an integral type
    }

In this example, the std::enable_if template class is used to conditionally enable the print_binary function only for integral types. The std::enable_if class has a static type member called type that is only defined if its boolean template argument is true. In this case, the typename std::enable_if<std::is_integral<T>::value>::type construct is used to define the return type of the print_binary function only for integral types.

Type traits can be used in a variety of ways in C++, such as for conditional compilation, template specialization, and generic programming. They are a powerful tool for enhancing the flexibility and generality of C++ code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics