且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SFINAE检查operator + =

更新时间:2023-11-27 19:07:04

我写第二个形式为:

  template< typename T> 
auto foo(T a,T b,...) - > decltype(a + = b,void())
{
a + = b;
}
$ p>

decltype的推导类型(a + = b,如果表达式 a + = b 有效,则void()void 将只是 void



好吧,即使在第一种形式中,我也会使用尾随返回类型方法。


I'm trying to eliminate an overload from an overload set if operator+= is missing.

I know how to check if T+T is legal :

template<typename T,
         typename CheckTplusT = decltype(std::declval<T>() + std::declval<T>())>
void foo(T a, T b, ...)
{
  a = a + b;
}

but this doesn't work for +=

template<typename T,
         typename CheckTplusT = decltype(std::declval<T>() += std::declval<T>())>
void foo(T a, T b, ...)
{
  a += b;
}

Is this fixable by using another expression inside decltype or do I need another SFINAE construct?

The reason I need this eliminated from the overload set is that it ***es with another overload that accepts a functor to be used as an alternative to +=. Compilers are VS2013, gcc4.8

I would write the second form as:

template<typename T>
auto foo(T a, T b, ...) -> decltype( a+=b, void() )
{
  a += b;
}

The deduced type for decltype(a+=b, void()) would be just void if the expression a+=b is valid, else it would result in SFINAE.

Well, even in the first form, I would use the trailing-return type approach.