有没有一种方法可以创建具有不同返回类型的c ++模板?

Soe*_*ann 3 c++ templates

我想知道是否有一种方法可以编写具有不同返回类型的C ++模板。

我的用例是从列表返回最大值的方法。

但是,由于我使用的是Qt框架,因此此函数应能够处理数字和QString值。当向该函数提供QString列表时,该函数应返回最大字符串的长度。如果传递数值,则输入类型应为返回类型。

我写的是这样的:

template< class T >
auto getMax( QList< T > aList ) -> decltype( std::is_arithmetic< T >::value ? T : int( 0 ) )
{
  if ( std::is_arithmetic< T >::value )
  {
      T Result( aList.isEmpty() ? 0 : aList.first() );
      for ( auto lElement : aList )
      {
          Result = std::max( Result, lElement );
      }

      return Result;
  }

  if ( std::is_same< T, QString >::value )
  {
      // List contains QString -> return length of largest string
      int Result( aList.isEmpty() ? 0 : aList.first().length() );

      for ( const QString & lrcsElement : aList )
      {
          Result = std::max( lrcsElement.length(), Result );
      }

      return Result;
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

该代码随VS 2017一起编译。

但是当我想使用这样的模板功能时

const QString sError  ( tr( "Error"       ) );
const QString sWarning( tr( "Warning"     ) );
const QString sInfo   ( tr( "Information" ) );
const QString sDebug  ( tr( "Debug "      ) );
auto iMaxTextLength( SMUtils::getMax< QString >( { sError, sWarning, sInfo, sDebug } ) );
Run Code Online (Sandbox Code Playgroud)

编译器给我一些错误信息:

  • 错误C2672:“ SMUtils :: getMax”:找不到匹配的重载函数。
  • 错误C2893:无法专用于功能模板“未知类型的SMUtils :: getMax(QList)”。
  • 错误C2119:“ li32MaxTextLength”:无法从空的初始化程序推导出“ auto”的类型。

当然,我可以编写一种专门的getMax( QStringList )方法,但是我想知道是否可以仅使用一个模板函数。

那有可能吗?如果可以,怎么办?

谢谢,Sören

Jar*_*d42 8

-> decltype( std::is_arithmetic< T >::value ? T : int( 0 ) )

应该

-> std::conditional_t<std::is_arithmetic<T>::value, T, int>;

甚至完全省略它,让编译器推论(但需要正确的返回类型,因此请参见if constexpr)。

和你的

if ( std::is_arithmetic< T >::value )
Run Code Online (Sandbox Code Playgroud)

应该

if constexpr ( std::is_arithmetic< T >::value )
Run Code Online (Sandbox Code Playgroud)