gpt4 book ai didi

c++ - std::begin 的 SFINAE 问题

转载 作者:太空狗 更新时间:2023-10-29 21:16:09 25 4
gpt4 key购买 nike

以下代码在 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 >() ) 的行static_assert 失败对于 int输入错误:

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{ } );

Live Demo

关于c++ - std::begin 的 SFINAE 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com