fix: explicitly check operator[] in is_contiguous (#4825)

Prevent false positives when the container itself does not have `operator[](size_t)`, but the target type of one of the non-explicit user-defined conversion functions does.
This commit is contained in:
Yat Ho 2026-06-26 03:21:59 +08:00 committed by GitHub
parent 588b3a0f8f
commit 0e601c34de
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 3 deletions

View File

@ -493,9 +493,10 @@ inline FMT_CONSTEXPR auto get_container(OutputIt it) ->
template <typename T, typename Enable = void>
struct is_contiguous : std::false_type {};
template <typename T>
struct is_contiguous<T, void_t<decltype(std::declval<T&>().data()),
decltype(std::declval<T&>().size()),
decltype(std::declval<T&>()[size_t()])>>
struct is_contiguous<T,
void_t<decltype(std::declval<T&>().data()),
decltype(std::declval<T&>().size()),
decltype(std::declval<T&>().operator[](size_t()))>>
: std::true_type {};
} // namespace detail

View File

@ -874,6 +874,24 @@ struct custom_container {
auto operator[](size_t) -> char& { return data; }
};
struct phantom_subscript_operator_container {
std::vector<char> buffer;
using value_type = char;
auto size() const noexcept -> size_t { return buffer.size(); }
auto data() noexcept -> char* { return buffer.data(); }
auto data() const noexcept -> const char* { return buffer.data(); }
void resize(size_t n) { buffer.resize(n); }
void push_back(const char& value) { buffer.push_back(value); }
operator const char*() const noexcept { return data(); }
};
FMT_BEGIN_NAMESPACE
template <> struct is_contiguous<custom_container> : std::true_type {};
FMT_END_NAMESPACE
@ -884,6 +902,7 @@ TEST(base_test, is_contiguous) {
EXPECT_TRUE((fmt::is_contiguous<fmt::string_view>::value));
EXPECT_TRUE((fmt::is_contiguous<std::vector<char>>::value));
EXPECT_FALSE((fmt::is_contiguous<std::list<char>>::value));
EXPECT_FALSE((fmt::is_contiguous<phantom_subscript_operator_container>::value));
}
TEST(base_test, format_to_custom_container) {