Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 20 additions & 19 deletions include/xtensor/utils/xutils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -283,29 +283,30 @@ namespace xt
* apply implementation *
************************/

namespace detail
{
template <class R, class F, std::size_t I, class... S>
R apply_one(F&& func, const std::tuple<S...>& s) NOEXCEPT(noexcept(func(std::get<I>(s))))
{
return static_cast<R>(func(std::get<I>(s)));
}

template <class R, class F, std::size_t... I, class... S>
R apply(std::size_t index, F&& func, std::index_sequence<I...> /*seq*/, const std::tuple<S...>& s)
NOEXCEPT(noexcept(func(std::get<0>(s))))
{
using FT = std::add_pointer_t<R(F&&, const std::tuple<S...>&)>;
static const std::array<FT, sizeof...(I)> ar = {{&apply_one<R, F, I, S...>...}};
return ar[index](std::forward<F>(func), s);
Copy link
Contributor Author

@spectre-ns spectre-ns Mar 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Potential access violation if index > I - 1.

}
}

template <class R, class F, class... S>
inline R apply(std::size_t index, F&& func, const std::tuple<S...>& s)
NOEXCEPT(noexcept(func(std::get<0>(s))))
{
return detail::apply<R>(index, std::forward<F>(func), std::make_index_sequence<sizeof...(S)>(), s);
XTENSOR_ASSERT(sizeof...(S) > index);
return std::apply(
[&](const S&... args) -> R
{
auto f_impl = [&](auto&& self, auto&& i, auto&& h, auto&&... t) -> R
{
if (i == index)
{
return static_cast<R>(func(h));
}
if constexpr (sizeof...(t) > 0)
{
return self(self, std::size_t{i + 1}, t...);
}
return R{};
};
return f_impl(f_impl, std::size_t{0}, args...);
},
s
);
}

/***************************
Expand Down
6 changes: 3 additions & 3 deletions test/test_xutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,16 @@ namespace xt
TEST(utils, apply)
{
ASSERT_TRUE(foo(std::make_tuple(1, 2, 3)) == 2);
EXPECT_FALSE(noexcept(foo(std::make_tuple(1, 2, 3))));
static_assert(!noexcept(foo(std::make_tuple(1, 2, 3))));
auto func_ne = [](int i) noexcept
{
return i;
};
auto t = std::make_tuple(1, 2, 3);
#if (_MSC_VER >= 1910)
EXPECT_FALSE(noexcept(apply<int>(1, func_ne, t)));
static_assert(!noexcept(apply<int>(1, func_ne, t)));
#else
EXPECT_TRUE(noexcept(apply<int>(1, func_ne, t)));
static_assert(noexcept(apply<int>(1, func_ne, t)));
#endif
}

Expand Down