如果给定模板不是运算符参数类型的专用模板,则禁用运算符重载

Disabling operators overloads if a given template is not specialized for the operator parameters type

本文关键字:运算符 专用 重载 参数 如果 类型      更新时间:2023-10-16

我正在编写一个元编程库,其中包括一组编译时算术类型和函数。例如:

元函数.hpp

template<typename T>
struct function
{
    using result = T;
};
template<typename LHS , typename RHS>
struct add_t;
//Add metafunction
template<typename LHS , typename RHS>
using add = typename add_t<LHS,RHS>::result;

fixed_point.hpp

#include "metafunctions.hpp"
template<long long int BITS , unsigned int PRECISSION>
struct fixed_point
{
    operator float()
    {
        return (float)BITS * std::pow(10.0f,-(float)PRECISION); //Its implemented as decimal fixed_point, not binary.
    };
};
//An alias which provides a convenient way to create numbers: scientific notation
template<int mantissa , int exponent = 0 , fbcount PRECISSION = mpl::DEFAULT_FRACTIONAL_PRECISION> // MANTISSA x 10^EXPONENT
using decimal = mpl::fixed_point<decimal_shift<mantissa , PRECISSION + exponent>::value , PRECISSION>; 
//add specialization:
template<long long int BITS1 , long long int BITS2 , unsigned int PRECISSION>
struct add_t<mpl::fixed_point<BITS1,PRECISION> , mpl::fixed_point<BITS2,PRECISION>> : public mpl::function<fixed_point<BITS1+BITS2 , PRECISION>> {};

几天前,我注意到我可以利用decltype关键字并实现表达式模板来简化复杂表达式的语法:

表达式.hpp

template<typename LHS , typename RHS>
mpl::add<LHS,RHS> operator+(const LHS& , const RHS&);
template<typename LHS , typename RHS>
mpl::sub<LHS,RHS> operator-(const LHS& , const RHS&);
template<typename LHS , typename RHS>
mpl::mul<LHS,RHS> operator*(const LHS& , const RHS&);
template<typename LHS , typename RHS>
mpl::div<LHS,RHS> operator/(const LHS& , const RHS&);

其用法示例:

using pi = mpl::decimal<3141592,-6>; //3141592x10⁻-6 (3,141592)
using r  = mpl::decimal<2,-2>; //0,002
using a  = mpl::decimal<1>; // 1,0 
using x = decltype( pi() * r() + ( r() / a() ) ); //pi*r + (r/a)

但这有一个缺点:重载是为任何类型的定义的,因此像"a string" + "other string"这样的表达式适合expressions.hpp operator+重载。当然,重载解析会导致编译错误,因为编译器试图将std::string拟合为 mpl::add_t 的类型参数。

我的问题是:有没有办法根据函数/运算符参数的特定模板(mpl::add_t示例中)的专用化来禁用/启用重载(使用 std::enable_if 或类似的东西?

因此,如果表达式的结果类型对参数类型具有专用性,则将启用运算符,并在其他情况下禁用运算符。

这样的事情可能会起作用:

template<typename LHS , typename RHS>
typename std::enable_if<
   !std::is_same<
       void,
       typename mpl::add_t<LHS,RHS>::result
    >::value,
    mpl::add<LHS,RHS>
>::type
operator+(const LHS& , const RHS&)
{
    // ...
}

依赖于这样一个事实,即当且仅当存在专业化时,存在 typedef add_t<LHS,RHS>::result(并且不是void)。