c++templatestypes

How to determine whether the template type is a basic type or a class


I have code something like this

template <typename T> void fun (T value)
{
    .....
    value.print ();  //Here if T is a class I want to call print (), 
                     //otherwise use printf
    .....
}

Now, to print the value, if T is a class, I want to call the print function of the object, but if T is a basic datatype, I just want to use printf.

So, how do I find if the Template type is a basic data type or a class?


Solution

  • You could use std::is_class (and possibly std::is_union). The details depend on your definition of "basic type". See more on type support here.

    But note that in C++ one usually overloads std::ostream& operator<<(std::ostream&, T) for printing user defined types T. This way, you do not need to worry about whether the type passed to your function template is a class or not:

    template <typename T> void fun (T value)
    {
        std::cout << value << "\n";
    }