Friday 9 August 2019

c++ - How to get the type of a template, like template , and to check if T is int or float or a class



the problem is described briefly as below:



template 
void display(T data){
if(is_int(T)) // how to check if T is int in this function is_int
printf(" %d", data);

if(is_float(T)) // how to check if T is float in this function is_float
printf(" %f", data);
if(is_class(T)) // how to check if T is class in this function is_class
data.display();
}


Here suppose that T can be type of int or float or a class.



If I define some variables and want to display their values using the same function:




int a = 10:
float b = 2.7;
A_Class c;

display(a);
display(b);
display(c);
display(new int(3));
display(new float(1.899));

display(new float(1));


I know that in C++, there is one solution for checking int and float(just for the issue of printing), that is to use std::cout, as explained in this question(C++ templates - How to find whether the template type is a basic type or a class).



And using std::is_integral::value doesn't apply for the case like this:



display(new int(3));
display(new float(1.899));
display(new float(1));



because these variables are classes not the basic types. So for this situation, how we judge the type(int or float) of new int(), new float()?


Answer



To print the int and float values just provide overloads of display() that take arguments of those types, respectively. For objects that contain a member function named display(), you can use SFINAE to selectively enable the free function form of display()



#include 
#include

template

auto display(T const& t) -> decltype(t.display(), void())
{
std::cout << "display(T const& t)\n";
}

void display(int)
{
std::cout << "display(int)\n";
}


void display(double)
{
std::cout << "display(double)\n";
}

struct foo
{
void display() const
{
std::cout << "foo::display\n";

}
};

struct bar {};

int main()
{
display(10);
display(10.0);
display(foo());

// display(bar()); // doesn't compile
}


Live demo of what happens when you call display(bar());



main.cpp:35:18: error: no matching function for call to 'display(bar)'

display(bar()); // doesn't compile
...

main.cpp:5:49: error: 'const struct bar' has no member named 'display'

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...