我正在尝试使用以下有效值来简洁地定义一个变量模板:
// (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
VecXX向量定义(SIMD向量)需要使用相应的标量类型,如图所示(例如huge<float>
用于float
s的向量)。可以通过VecXX::value_type
或类型特征样式模板类(VectorTraits<VecXX>::value_type
)来获得。
理想情况下,我想我会有类似的东西:
// 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>);
但是我还不太清楚可以使用的版本(上面的失败是“重新定义const T huge<T>
”)。最好的方法是什么?
答案 0 :(得分:2)
并非完全是您的要求,但我希望以下示例可以向您展示如何使用SFINAE来专门化模板变量
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};
您可以使用
进行检查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;
答案 1 :(得分:0)
将@ max66的答案保留为学分,但这是我想出的具体解决方案:
struct _VectorTraits { static constexpr bool is_vector = true; };
template<class T> struct VectorTraits : _VectorTraits { static constexpr bool is_vector = false; };
template<> struct VectorTraits<Vec4f> : _VectorTraits { typedef float value_type; };
template<> struct VectorTraits<Vec8f> : _VectorTraits { typedef float value_type; };
template<> struct VectorTraits<Vec4d> : _VectorTraits { typedef double value_type; };
template<typename T> using EnableIfFP = std::enable_if_t<std::is_floating_point<T>::value>;
template<typename T> using EnableIfVec = std::enable_if_t<VectorTraits<T>::is_vector>;
template<typename T> constexpr T EXP = std::numeric_limits<T>::max_exponent / 2;
// Actual variable template, finally:
template<typename T, typename Enabler = void> const T huge = T{ 0 };
template<typename T> const T huge<T, EnableIfFP<T> > = std::scalbn(1, EXP<T>);
template<typename T> const T huge<T, EnableIfVec<T> > = T{ huge<typename VectorTraits<T>::value_type> };
我认为这仍然可以改善:
T
在每个专业的左侧出现4次。huge<uint32_t>
)仍然使用无意义的0
值进行编译。我希望他们不要编译。