[英]Why using SFINAE to find if a method exists fails with std::vector::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,表達式需要依賴於模板的直接上下文中的模板參數,即模板參數列表。
簡單的修復是默認U
到T
並在您的依賴表達式中使用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.