Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial class specialization using type traits

I am pretty new to C++, and I have run into an issue I can't seem to fix or find someone else who had the same issue.

I have a class Polynomial as defined:

template<class C>
class Polynomial {
    std::vector<C> coefficients;
    ...
public:
    ...
    const double integral(double, double);
    ...
};

I need to make sure, that the integral() method can not be called if C is an integral type. Obviously that means using type traits, HOWEVER I have tried using template<typename = typename std::enable_if<!std::is_integral<C>::value, C>::type> on the method itself, and although it would compile, I could now not make an object with integral types as the template argument.

I then thought, that it should be possible to create partial specializations of the Polynomial class, that is to have a specialization of the class with floating points, one with integral and one with complex numbers. Something along the lines of

template<typename C>
class Polynomial<typename std::enable_if<std::is_floating_point<C>::value, C>::type> : Polynomial<C> {
public:
    const double integral(double, double);
};

However, not matter how I do this, it never seems to work.

I guess the question I have is: How is it possible to specify a partial specialization of classes using type traits as the specialization?

I hope you can help.

like image 339
Chraebe Avatar asked Dec 23 '22 06:12

Chraebe


1 Answers

You need a separate base class for the common stuff, then you can make the template specializations for Polynomial like this:

template<class C>
class PolynomialBase {
    std::vector<C> coefficients;
};    

template <typename T, typename Enable = void>
class Polynomial;

template<typename C>
class Polynomial<C, typename std::enable_if<!std::is_integral<C>::value>::type> : PolynomialBase<C> {
public:
     const double integral(double, double);
};    

template<typename C>
class Polynomial<C, typename std::enable_if<std::is_integral<C>::value>::type> : PolynomialBase<C> {};
like image 183
krisz Avatar answered Dec 28 '22 06:12

krisz