std::derived_from(3)

πŸ“¦
version 2024.07.05 Β· 3 versions
, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::derived_from(3) β€” from the C++ Standard Libary manual πŸ’–

Ok so bestie, welcome to the cutest concept page in the C++ Standard Libary manual. (Yes, β€œLibary” β€” we’re keeping the typo because it’s part of the lore.) This one is all about asking β€œis this type derived from that type?” and the answer is dripped out in template constraints. Let’s get into it πŸ¦‹βœ¨


πŸŽ€ NAME πŸŽ€

std::derived_from - std::derived_from

That’s it. The NAME section said what it said, and honestly? Minimalist queen. πŸ’…


✨ Synopsis ✨

Defined in header <concepts> β€” and this whole vibe is (since C++20), no cap.

Defined in header <concepts>
template< class Derived, class Base >

concept derived_from =
    std::is_base_of_v<Base, Derived> &&
(since C++20)

    std::is_convertible_v<const volatile Derived*, const volatile Base*>;

The concept derived_from<Derived, Base> is satisfied if and only if Base is a class type that is either Derived or a public and unambiguous base of Derived, ignoring cv-qualifiers. Periodt. 🫢

Also note, bestie: this behavior is different to std::is_base_of when Base is a private or protected base of Derived. That’s the plot twist, and it matters. 🌸


🌸 Example 🌸

The example is labeled // Run this code β€” go run it, it’s giving compiler-validation realness. πŸ”₯

#include <concepts>

class A {};

class B : public A {};

class C : private A {};

// std::derived_from == true only for public inheritance or exact same class
static_assert(std::derived_from<B, B> == true);      // same class: true
static_assert(std::derived_from<int, int> == false); // same primitive type: false
static_assert(std::derived_from<B, A> == true);      // public inheritance: true
static_assert(std::derived_from<C, A> == false);     // private inheritance: false

// std::is_base_of == true also for private inheritance
static_assert(std::is_base_of_v<B, B> == true);      // same class: true
static_assert(std::is_base_of_v<int, int> == false); // same primitive type: false
static_assert(std::is_base_of_v<A, B> == true);      // public inheritance: true
static_assert(std::is_base_of_v<A, C> == true);      // private inheritance: true

int main() {}

πŸ‘‘ See also πŸ‘‘

  • is_base_of β€” checks if a type is derived from the other type. (C++11) (class template) ✨
  • is_convertible β€” checks if a type can be converted to the other type. (C++11) (class template) πŸ’–
  • is_nothrow_convertible β€” checks if a type can be converted to the other type. (C++20) (class template) πŸ¦‹

🫢 Source/version/date check: this page is from http://cppreference.com, stamped 2024.06.10, and filed under std::derived_from(3). That’s the footer, bestie β€” she ate and left no crumbs. Bye! πŸ’–βœ¨
πŸ“¦ where this page comes from