Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 728
Hashken Avatar asked Apr 21 '13 14:04

Hashken


People also ask

What are the two types of templates?

There are two types of templates in C++, function templates and class templates.

How do you define a template class?

Definition. As per the standard definition, a template class in C++ is a class that allows the programmer to operate with generic data types. This allows the class to be used on many different data types as per the requirements without the need of being re-written for each type.

Is template class A generic class?

Key differences between generics and C++ templates: Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime.


2 Answers

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";
}
like image 181
juanchopanza Avatar answered Oct 05 '22 23:10

juanchopanza


Recommend overloading operator<<(std::ostream&) for any type T instead of using printf(): how would you know what format specifier to use?

template <typename T> void fun (T value)
{
    .....
    std::cout << value <<  std::endl;
    .....
}

FWIW, std::is_class exists.

like image 26
hmjd Avatar answered Oct 05 '22 23:10

hmjd