如果给定模板不是运算符参数类型的专用模板,则禁用运算符重载
Disabling operators overloads if a given template is not specialized for the operator parameters type
我正在编写一个元编程库,其中包括一组编译时算术类型和函数。例如:
元函数.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
)。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 调用专用模板时出错"no matching function for call to [...]"
- 仅为某些模板专用化定义转换运算符:预期类型/预期类型说明符
- 专用运算符<<模板类的模板类的另一个类
- 使用 = 的模板运算符专用化
- 运算符<<重载时无法访问专用成员(指定指针)
- 来自另一个类的模板运算符专用化
- 运算符重载和模板专用化
- 重载运算符'<<'(左移)的显式专用化
- 如果给定模板不是运算符参数类型的专用模板,则禁用运算符重载
- 为什么 std::atomic<integral> 专用化不提供乘法和除法赋值运算符?
- 类具有运算符()时的结构专用化
- 无法专用化函数模板。重载运算符<<
- 无法访问QXmlStreamReader的专用成员(运算符=)
- C++模板专用化:更改运算符()的返回类型