If I have an object a
that either a built-in array or a class-type with a suitable operator []
, and its returned type can be indexed itself, how should
I've come up with a solution, based on the comment by @luc-danton and answer by @user315052.
#include
template < typename Base, typename ...Indices >
class indexing_result;
template < typename T >
class indexing_result
{
public:
using type = T;
static constexpr
bool can_throw = false;
};
template < typename T, typename U, typename ...V >
class indexing_result
{
using direct_type = decltype( std::declval()[std::declval()] );
using next_type = indexing_result;
static constexpr
bool direct_can_throw
= not noexcept( std::declval()[std::declval()] );
public:
using type = typename next_type::type;
static constexpr
bool can_throw = direct_can_throw || next_type::can_throw;
};
template < typename T >
inline constexpr
auto slice( T &&t ) noexcept -> T &&
{ return static_cast(t); }
template < typename T, typename U, typename ...V >
inline constexpr
auto slice( T &&t, U &&u, V &&...v )
noexcept( !indexing_result::can_throw )
-> typename indexing_result::type
{
return slice( static_cast(t)[static_cast( u )],
static_cast(v)... );
}
I put a full example program up as a Gist. It worked on a web-site compiler running GCC >= 4.7, CLang >= 3.2, and Intel C++ >= 13.0.