Get template function type

I'm new to using templates in C ++, I want to do different things depending on the type used between < and > , so function<int>() and function<char>() will not do the same. How can I achieve this?

 template<typename T> T* function() { if(/*T is int*/) { //... } if(/*T is char*/) { //... } return 0; } 
+4
source share
5 answers

You want to use the explicit specialization of your function template:

 template<class T> T* function() { }; template<> int* function<int>() { // your int* function code here }; template<> char* function<char>() { // your char* function code here }; 
+6
source

Create Template Specialization :

 template<typename T> T* function() { //general case general code } template<> int* function<int>() { //specialization for int case. } template<> char* function<char>() { //specialization for char case. } 
+5
source

Best practices include tagging because specialization is complex.

Sending tags is easier to use quite often:

 template<typename T> T* only_if_int( std::true_type is_int ) { // code for T is int. // pass other variables that need to be changed/read above } T* only_if_int( std::false_type ) {return nullptr;} template<typename T> T* only_if_char( std::true_type is_char ) { // code for T is char. // pass other variables that need to be changed/read above } T* only_if_char( std::false_type ) {return nullptr;} template<typename T> T* function() { T* retval = only_if_int( std::is_same<T, int>() ); if (retval) return retval; retval = only_if_char( std::is_same<T, char>() ); return retval; } 
+1
source
 template<class T> T Add(T n1, T n2) { T result; result = n1 + n2; return result; } 

For a detailed understanding of the template, follow the link below: http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-1

0
source

you can define overloaded functions like this:

 #define INTT 0 #define CHARR 1 template<typename T> T* function() { int type; type = findtype(T); //do remaining things based on the return type } int findType(int a) { return INTT; } int findType(char a) { return CHARR; } 
-one
source

Source: https://habr.com/ru/post/1497984/


All Articles