Skip to content

Commit 5709ccf

Browse files
committed
Also apply ambiguous conversion workaround to str()
1 parent 3428195 commit 5709ccf

File tree

3 files changed

+6
-1
lines changed

3 files changed

+6
-1
lines changed

include/pybind11/pytypes.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1090,8 +1090,10 @@ class str : public object {
10901090
str(const std::string &s) : str(s.data(), s.size()) { }
10911091

10921092
#ifdef PYBIND11_HAS_STRING_VIEW
1093+
// enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
1094+
template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
10931095
// NOLINTNEXTLINE(google-explicit-constructor)
1094-
str(std::string_view s) : str(s.data(), s.size()) { }
1096+
str(T s) : str(s.data(), s.size()) { }
10951097

10961098
# ifdef PYBIND11_HAS_U8STRING
10971099
// reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char)

tests/test_builtin_casters.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,8 @@ TEST_SUBMODULE(builtin_casters, m) {
167167
};
168168
m.def("bytes_from_type_with_both_operator_string_and_string_view",
169169
[]() { return py::bytes(TypeWithBothOperatorStringAndStringView()); });
170+
m.def("str_from_type_with_both_operator_string_and_string_view",
171+
[]() { return py::str(TypeWithBothOperatorStringAndStringView()); });
170172
#endif
171173

172174
// test_integer_casting

tests/test_builtin_casters.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ def test_string_view(capture):
215215
assert m.string_view_memoryview() == "Have some 🎂".encode()
216216

217217
assert m.bytes_from_type_with_both_operator_string_and_string_view() == b"success"
218+
assert m.str_from_type_with_both_operator_string_and_string_view() == "success"
218219

219220

220221
def test_integer_casting():

0 commit comments

Comments
 (0)