Search code examples
c++type-traitsstd-pair

When would std::is_convertible_v<const type &, type> be false?


I was reading the rules of the constructors for std::pair (as documented on cppreference) when I came across this ruling:

This constructor is explicit if and only if std::is_convertible_v<const first_type&, first_type> is false or std::is_convertible_v<const second_type&, second_type> is false.

std::is_convertible_v<From, To> is true if From is implicitly convertible to To, and false if that is not the case.

But under what circumstance would a case like std::is_convertible_v<const T &, T> be false? I've been thinking about it for a while and I can't actually think of any offhand. It seems to me that a reference to a const value of type T would always be convertible to a value of type T.


Solution

  • std::is_convertible_v checks for an implicit conversion. std::is_convertible_v<const T &, T> returns true if there exists an implicit copy constructor for T.

    struct S {
      explicit S(const S &) = default;
    };
    

    S has an explicit copy constructor so std::is_copy_constructible_v<S> is true but std::is_convertible_v<const S &, S> is false. The copy constructor of std::pair should be explicit to match the copy constructor of first_type so it makes sense that the copy constructor of std::pair is explicit when std::is_convertible_v<const first_type &, first_type> is false.