std::is_con..._convertible(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

okay so bestie, welcome to the std::is_con..._convertible(3) page from the C++ Standard Libary manual β€” yes that exact spelling is in the header and we are keeping it because details are sacred πŸ’…. today’s main characters are std::is_convertible and std::is_nothrow_convertible, two <type_traits> icons that answer the extremely important question: can this type become that type without the compiler having a whole crisis? ✨

πŸ’– NAME πŸ’–

  • std::is_convertible,std::is_nothrow_convertible β€” std::is_convertible,std::is_nothrow_convertible

🌸 Synopsis 🌸

both of these live in the header <type_traits>, obviously:

Defined in header <type_traits>
template< class From, class To > (1) (since C++11)
struct is_convertible;
template< class From, class To > (2) (since C++20)
struct is_nothrow_convertible;

okay so here’s the tea for each one:

(1) is_convertible β€” if the imaginary function definition

To test() { return std::declval<From>(); }

is well-formed, (that is, either std::declval<From>() can be converted to To using implicit conversions, or both From and To are possibly cv-qualified void), it provides the member constant value equal to true. otherwise value is false. for the purposes of this check, the use of std::declval in the return statement is not considered an ODR-use.

(since C++26) if To is a reference type and a temporary object would be created when binding std::declval<From>() to To, the return statement in the imaginary function is considered well-formed, even though such binding is ill-formed in an actual function.

access checks are performed as if from a context unrelated to either type. only the validity of the immediate context of the expression in the return statement (including conversions to the return type) is considered.

(2) is_nothrow_convertible β€” same as (1), but the conversion is also noexcept.

🚨 undefined behavior alert, and we are not kidding around: if From or To is not a complete type, (possibly cv-qualified) void, or an array of unknown bound, the behavior is undefined. also, if an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined. and if the program adds specializations for any of the templates described on this page, the behavior is undefined. periodt. πŸ’€

πŸŽ€ Member constants πŸŽ€

  • value β€” true if From is convertible to To, false otherwise; [static] (public static member constant)

πŸ¦‹ Member functions πŸ¦‹

  • operator bool β€” converts the object to bool, returns value (public member function)
  • operator() β€” returns value (C++14) (public member function)

✨ Member types ✨

  • value_type β€” bool
  • type β€” std::integral_constant<bool, value>

πŸ’… Possible implementation πŸ’…

here’s the implementation for (1) is_convertible, and honestly it’s giving template wizardry:

namespace detail
{
    template<class T>
    auto test_returnable(int) -> decltype(
        void(static_cast<T(*)()>(nullptr)), std::true_type{}
    );
    template<class>
    auto test_returnable(...) -> std::false_type;

    template<class From, class To>
    auto test_implicitly_convertible(int) -> decltype(
        void(std::declval<void(&)(To)>()(std::declval<From>())), std::true_type{}
    );
    template<class, class>
    auto test_implicitly_convertible(...) -> std::false_type;
} // namespace detail

template<class From, class To>
struct is_convertible : std::integral_constant<bool,
    (decltype(detail::test_returnable<To>(0))::value &&
     decltype(detail::test_implicitly_convertible<From, To>(0))::value)
||
    (std::is_void<From>::value && std::is_void<To>::value)
> {};

and here’s (2) is_nothrow_convertible, with the noexcept glow-up:

template<class From, class To>
struct is_nothrow_convertible : std::conjunction<std::is_void<From>, std::is_void<To>> {};

template<class From, class To>
    requires
        requires
        {
            static_cast<To(*)()>(nullptr);
            { std::declval<void(&)(To) noexcept>()(std::declval<From>()) } noexcept;
        }
struct is_nothrow_convertible<From, To> : std::true_type {};

🌈 Notes 🌈

it gives well-defined results for reference types, void types, array types, and function types. iconic behavior honestly.

currently the standard has not specified whether the destruction of the object produced by the conversion (either a result object or a temporary bound to a reference) is considered as a part of the conversion. this is LWG issue 3400.

all known implementations treat the destruction as a part of the conversion, as proposed in P0758R1.

feature-test macro tea β˜•:

  • __cpp_lib_is_nothrow_convertible β€” 201806L β€” (C++20) β€” std::is_nothrow_convertible

πŸ“ Example πŸ“

the original literally says // Run this code, so bestie, go run it:

#include <iomanip>
#include <iostream>
#include <string>
#include <string_view>
#include <type_traits>

class E { public: template<class T> E(T&&) {} };

int main()
{
    class A {};
    class B : public A {};
    class C {};
    class D { public: operator C() { return c; } C c; };

    static_assert(std::is_convertible_v<B*, A*>);
    static_assert(!std::is_convertible_v<A*, B*>);
    static_assert(std::is_convertible_v<D, C>);
    static_assert(!std::is_convertible_v<B*, C*>);
    // Note that the Perfect Forwarding constructor makes the class E be
    // "convertible" from everything. So, A is replaceable by B, C, D..:
    static_assert(std::is_convertible_v<A, E>);

    static_assert(!std::is_convertible_v<std::string_view, std::string>);
    static_assert(std::is_convertible_v<std::string, std::string_view>);

    auto stringify = []<typename T>(T x)
    {
        if constexpr (std::is_convertible_v<T, std::string> or
                      std::is_convertible_v<T, std::string_view>)
            return x;
        else
            return std::to_string(x);
    };

    using std::operator "" s, std::operator "" sv;
    const char* three = "three";

    std::cout << std::quoted(stringify("one"s)) << ' '
              << std::quoted(stringify("two"sv)) << ' '
              << std::quoted(stringify(three)) << ' '
              << std::quoted(stringify(42)) << ' '
              << std::quoted(stringify(42.0)) << '\n';
}

πŸ‘‘ Output πŸ‘‘

"one" "two" "three" "42" "42.000000"

🫢 See also 🫢

  • is_base_of (C++11) β€” checks if a type is derived from the other type (class template)
  • is_pointer_interconvertible_base_of (C++20) β€” checks if a type is a pointer-interconvertible (initial) base of another type (class template)
  • is_pointer_interconvertible_with_class (C++20) β€” checks if objects of a type are pointer-interconvertible with the specified subobject of that type (function template)
  • convertible_to (C++20) β€” specifies that a type is implicitly convertible to another type (concept)

that’s the whole page bestie β€” and the footer details, preserved with love: source/version/date are http://cppreference.com, 2024.06.10, and std::is_con..._convertible(3). mwah πŸ’‹

πŸ“¦ where this page comes from