Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template specialization for fundamental types

Is there any way to make a template specialization for fundamental types only? I have tried to do the following:

template<typename T, typename = typename std::enable_if<!std::is_fundamental<T>::value>::type>
class foo
{
}

template<typename T, typename = typename std::enable_if<std::is_fundamental<T>::value>::type>
class foo
{
}

But I'm getting an error that the template is already defined.

like image 872
Andreas Loanjoe Avatar asked Jul 21 '17 18:07

Andreas Loanjoe


People also ask

What is a template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

What are templates and its types?

Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Generic Programming is an approach to programming where generic types are used as parameters in algorithms to work for a variety of data types.In C++, a template is a straightforward yet effective tool.

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.


1 Answers

Here you are creating two templated classes with the same name, not specializations.

You need to create a generic one and then specialize it:

// not specialized template (for non-fundamental types), Enabler will 
// be used to specialize for fundamental types
template <class T, class Enabler = void>
class foo { };

// specialization for fundamental types
template <class T>
class foo<T, std::enable_if_t<std::is_fundamental<T>::value>> { };
like image 60
Holt Avatar answered Oct 09 '22 19:10

Holt