I'm trying to create a class that works with integral and floating point types, but rejects any others. I got the following to work, where the generic template gets rejected using static_assert:
Code:
#include <iostream>
#include <type_traits>
#include <utility>
using namespace std;
template<typename T, typename Enable = void>
class X
{
static_assert(is_arithmetic_v<T>,
"X must be instantiated with integral or floating-point template argument.");
};
template<typename T>
class X<T, enable_if_t<is_integral_v<T>>>
{
public:
X() { cout << "X<integral type>()" << endl; }
};
template<typename T>
class X<T, enable_if_t<is_floating_point_v<T>>>
{
public:
X() { cout << "X<float type>()" << endl; }
};
class P {};
int main()
{
X<long> x1;
X<double> x2;
X<P> x3; // prevented by failing static assertion
}
Is there a way to only use two class templates for this scenario, making the generic version redundant?