Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template specialization by type groups combined with basic type

I would like to specialize template by group of types and also by extra definition for some specific simple types. Is it in C++11 and boost 1.60 possible? Following pseudocode illustrates my intention:

template <typename T> // Universal definition
struct convert
{  ...  }

template <> /* Definition for integral types like defined by std::type_traits */
struct convert<integral_types>
{  ...  }

template <> /* Definition for floating point types like defined by type_traits */
struct convert<floating_types>
{  ...  }

template <> /* Exception from integral types - specific definition */
struct convert<char>
{  ...  }

I think this could be solved by tag dispatcher, but I'm not sure if it's best solution. Another option is enable_if, combined with is_integral (and similar groups) , but simple char type is problem...

like image 245
user283474 Avatar asked Mar 21 '16 19:03

user283474


People also ask

What does template <> mean in C++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

What are the different types of templates we can do in C++?

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

What is the difference between function template and class template in C++?

For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.

Which of the datatypes are supported by template?

template<typename T> (This is more general than marking parameter T as a class or struct or union , as it can also include primitive types like int , bool , etc.) Integral constants, i.e. template<int i> .


1 Answers

You may do something like:

template <typename T, typename Enabler = void> // Universal definition
struct convert
{  ...  };

template <typename T> /* Definition for integral types like defined by std::type_traits */
struct convert<T, std::enable_if_t<std::is_integral<T>::value>>
{  ...  };

template <> /* Exception from integral types - specific definition */
struct convert<char, void>
{  ...  };
like image 119
Jarod42 Avatar answered Oct 27 '22 19:10

Jarod42