Monad
Monad

Reputation: 720

Differences between std::is_convertible and std::convertible_to (in practice)?

According to en.cppreference.com (from what I can gather):

The requirement imposed by std::is_convertible seems relatively straight-forward. Conversely, the r-value reference casting requirement of std::convertible_to seems oddly specific for such a generic concept that is shown in simple examples for C++20 features.

Being a novice in C++, I could not quite understand some terminology and parts of the supplementary descriptions provided in both webpages and I cannot imagine the exact difference between the requirements of either.

Some inter-related questions:

A simpler explanation or an example would help. Thank you!

Upvotes: 43

Views: 6523

Answers (1)

Barry
Barry

Reputation: 302738

std::is_convertible<From, To> (the type trait) checks is type From is implicitly convertible to type To.

std::convertible_to<From, To> (the concept) checks that From is both implicitly and explicitly convertible to To. It's rare that this is not the case, such types are ridiculous, but it's nice in generic code to just not have to worry about that case.

One example:

struct From;
struct To {
    explicit To(From) = delete;
};
struct From {
    operator To();
};

static_assert(std::is_convertible_v<From, To>);
static_assert(not std::convertible_to<From, To>);

Upvotes: 44

Related Questions