Standard conversion, user-defined conversion, explicit conversion và narrowing tham gia overload resolution như thế nào?
Xem đáp án và giải thích
Với mỗi overload khả thi, C++ tạo implicit conversion sequence cho từng argument rồi xếp hạng candidate bằng các rule như exact match, promotion và conversion. User-defined conversion sequence có thể dùng một converting constructor hoặc conversion function cùng standard conversion bao quanh; các sequence cạnh tranh có thể làm call ambiguous. Constructor hoặc conversion function khai báo explicit bị loại khỏi context implicit conversion thông thường, dù direct initialization và explicit cast có thể chọn chúng theo rule riêng. List initialization có các phase overload đặc biệt và từ chối narrowing conversion, nên brace có thể chủ ý làm interface chặt hơn parenthesis. Cast không sửa ownership hay range contract kém; nó chỉ yêu cầu một conversion cụ thể. Tránh implicit conversion operator quá rộng và single-argument converting constructor nếu substitutability không được chủ ý, dùng explicit để bảo vệ domain boundary, đồng thời xem toàn bộ overload set thay vì chỉ suy luận từ destination type.
Với mỗi overload khả thi, C++ tạo implicit conversion sequence cho từng argument rồi xếp hạng candidate bằng các rule như exact match, promotion và conversion. User-defined conversion sequence có thể dùng một converting constructor hoặc conversion function cùng standard conversion bao quanh; các sequence cạnh tranh có thể làm call ambiguous. Constructor hoặc conversion function khai báo explicit bị loại khỏi context implicit conversion thông thường, dù direct initialization và explicit cast có thể chọn chúng theo rule riêng. List initialization có các phase overload đặc biệt và từ chối narrowing conversion, nên brace có thể chủ ý làm interface chặt hơn parenthesis. Cast không sửa ownership hay range contract kém; nó chỉ yêu cầu một conversion cụ thể. Tránh implicit conversion operator quá rộng và single-argument converting constructor nếu substitutability không được chủ ý, dùng explicit để bảo vệ domain boundary, đồng thời xem toàn bộ overload set thay vì chỉ suy luận từ destination type.
Hãy liên hệ trực tiếp kết luận với kiểu, lifetime, ownership, overload resolution hoặc library contract xuất hiện trong câu hỏi. Nếu kết quả phụ thuộc implementation hoặc vi phạm precondition, cần nói rõ thay vì chỉ đoán output.