I have the following code:
template<typename T>
class Data
{
public:
int size() const;
private:
T m_data;
};
I want to implement the size() method using template specialisation methods. For a std::string it would look like this (in the .cpp):
template<>
int Data<std::string>::size() const
{
// code here
}
Now I would like to make a single specialisation for all arithmetic types. My initial thought was (in the .hpp):
template<typename T,
typename std::enable_if<std::is_arithmetic<T>::value, T>::type>
int Data<T>::size() const
{
// code here
}
However that throws a '/Data.hpp:29:1: Too many template parameters in template redeclaration'. How can I make a partial specialisation for all arithmetic types?
Edit: Correctly working by following cppreference's example:
template<typename T, typename Enable = void>
class Data
{
public:
int size() const { std::cout << "generic\n"; return 0; }
protected:
T m_data;
};
template<typename T>
class Data<T, typename std::enable_if<std::is_arithmetic<T>::value>::type>
{
public:
int size() const { std::cout << "arithmetic\n"; return 0; }
protected:
T m_data;
};
Doing:
Data<int> intData;
intData.size();
Results in 'arithmetic' being printed