Search code examples
c++c++14sfinaeenable-ifvariable-templates

Multiple variable template specializations with std::enable_if


I'm trying to concisely define a variable template with these effective values:

// (template<typename T> constexpr T EXP = std::numeric_limits<T>::max_exponent / 2;)

// float and double scalar definitions:
const double huge = std::scalbn(1, EXP<double>);
const float huge = std::scalbn(1, EXP<float>);
// SIMD vector definitions:
const Vec8f huge = Vec8f(huge<float>); // vector of 8 floats
const Vec8d huge = Vec8d(huge<double>); // vector of 8 doubles
const Vec4f huge = Vec4f(huge<float>); // vector of 4 floats
// Integral types should fail to compile

The VecXX vector definitions (SIMD vectors) need to use the corresponding scalar type as shown (e.g. huge<float> for vector of floats). This is available as VecXX::value_type or through a type traits-style template class (VectorTraits<VecXX>::value_type).

Ideally I think I'd have something like:

// Primary. What should go here? I want all other types to not compile
template<typename T, typename Enabler = void>
const T huge = T{ 0 };

// Scalar specialization for floating point types:
template<typename T>
const T huge<T> = std::enable_if_t<std::is_floating_point<T>::value, T>(std::scalbn(1, EXP<T>));

// Vector specialization, uses above declaration for corresponding FP type
template<typename T>
const T huge<T> = std::enable_if_t<VectorTraits<T>::is_vector, T>(huge<VectorTraits<T>::scalar_type>);

but I can't quite figure out a working version (above fails with "redefinition of const T huge<T>"). What's the best way to do this?


Solution

  • Not exactly what you asked but I hope the following example can show you how to use SFINAE to specialize a template variable

    template <typename T, typename = void>
    constexpr T huge = T{0};
    
    template <typename T>
    constexpr T huge<T, std::enable_if_t<std::is_floating_point<T>{}>> = T{1};
    
    template <typename T>
    constexpr T huge<std::vector<T>> = T{2};
    

    You can check it with

    std::cout << huge<int> << std::endl;
    std::cout << huge<long> << std::endl;
    std::cout << huge<float> << std::endl;
    std::cout << huge<double> << std::endl;
    std::cout << huge<long double> << std::endl;
    std::cout << huge<std::vector<int>> << std::endl;