簡體   English   中英

SFINAE與std :: begin的問題

[英]SFINAE problems with std::begin

以下代碼適用於Visual Studio 2013,但無法使用clang或gcc進行編譯,因此我猜測它不是有效的c ++。

#include <iterator>
#include <type_traits>
#include <vector>

template< typename T >
class SupportsStdBegin
{
  // std::false_type TestHasBegin( ... ) always exists.
  template< typename >
  static std::false_type TestSupportsBegin( ... );
  // std::true_type TestHasBegin( int ) only exists if std::begin( T() ) is a valid expression.
  template< typename U >
  static auto TestSupportsBegin( int ) -> decltype( std::begin( std::declval< T >() ), std::true_type{ } );

public:
  static const bool value = decltype( TestSupportsBegin< T >( 0 ) )::value;
};

static_assert( !SupportsStdBegin< int >::value, "'int' does not support std::begin()." );

const int TestArray[] = { 0, 1, 2, 3, 4, };
static_assert( SupportsStdBegin< decltype( TestArray ) >::value, "'const int TestArray[]' supports std::begin()." );

static_assert( SupportsStdBegin< std::vector< int > >::value, "'std::vector< int >' supports std::begin()." );

有人可以解釋為什么SFINAE不能像我期望的那樣工作嗎?

包含decltype( std::begin( std::declval< T >() )的行對於int類型的static_assert失敗,並帶有錯誤:

error: no matching function for call to 'begin(int)'

我認為這意味着SFINAE會失敗,返回std::false_type的實現將用於設置SupportsStdBegin< T >::value

我知道有其他方法可以編寫此測試,但我想知道為什么這種特殊方法無效。 我之前成功使用它來測試成員函數是否存在。

為了發生SFINAE,表達式需要依賴於模板的直接上下文中的模板參數,即模板參數列表。

簡單的修復是默認UT並在您的依賴表達式中使用U

template <typename U=T>
static auto TestSupportsBegin( int ) 
    -> decltype( std::begin( std::declval< U >() ), std::true_type{ } );

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM