Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::is_convertible — testing implicit conversion

std::is_convertible checks at compile time whether From can be implicitly converted to To. std::is_convertible_v exposes the same bool value without ::value; success does not guarantee value preservation or freedom from exceptions.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <type_traits>

std::is_convertible<From, To>::value
std::is_convertible_v<From, To>

In <type_traits>, the trait std::is_convertible<From, To> exposes a bool constant through ::value. The variable template std::is_convertible_v<From, To> is shorthand for that same value. The source type comes first, followed by the destination type.

The test models To test() { return std::declval<From>(); }: it checks whether the implicit conversion is well-formed without performing it. Access is checked from a context unrelated to either type; only the expression's immediate context is considered.

An explicit constructor is insufficient, although std::is_constructible_v<To, From> may be true. References and const matter. A true result guarantees neither losslessness nor freedom from exceptions.

From and To must each be a complete type, void with or without cv-qualifiers, or an array of unknown bound. Do not pass an incomplete class by value. Meeting this requirement is not enough: if the instantiation depends directly or indirectly on an incomplete object type and completing that type could change the result, the behavior is undefined. For example, Derived* and Base* are complete pointer types, but testing the conversion from Derived* to Base* has undefined behavior if completing Derived could change the result.

The example contrasts implicit and explicit constructors and checks reference binding.

Examples

#include <iostream>
#include <type_traits>

struct Implicit {
    Implicit(int) {}
};

struct Explicit {
    explicit Explicit(int) {}
};

static_assert(std::is_convertible<int, Implicit>::value);
static_assert(!std::is_convertible_v<int, Explicit>);
static_assert(std::is_constructible_v<Explicit, int>);
static_assert(std::is_convertible_v<int&, const int&>);
static_assert(!std::is_convertible_v<const int&, int&>);

int main() {
    std::cout << std::boolalpha
              << std::is_convertible<int, Implicit>::value << '\n'
              << std::is_convertible_v<int, Explicit> << '\n';
}

Result

true
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources