CKTIS / C++
std::convertible_to — consistent implicit and explicit conversion
std::convertible_to<From, To>, declared in <concepts>, requires both implicit conversion and conversion through static_cast to To, with consistent results. Merely supporting an explicit cast is not sufficient.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
template<class From, class To>
concept convertible_to =
std::is_convertible_v<From, To> &&
requires { static_cast<To>(std::declval<From>()); };std::convertible_to<From, To>, declared in <concepts>, constrains templates. Its definition combines std::is_convertible_v<From, To> with the validity of static_cast<To>(std::declval<From>()). It considers the type and value category of std::declval<From>(), so qualifiers and references in From matter.
The implicit and explicit conversions must produce equal results when To is an object type or a reference to an object. This is a semantic requirement, not merely a syntax check: a result of true does not prove that the compiler checked the behavior of user-defined conversions.
If std::add_rvalue_reference_t<From> is a reference to an object, the conversions must not modify the source object unless it is an rvalue reference to a non-const type. In that exception, the object may be left in a valid but unspecified state. This condition does not apply when the source is not a reference to an object.
In the example, short satisfies the constraint on as_int. ExplicitOnly supports static_cast<int>, but its explicit operator int() does not provide implicit conversion, so the concept is false. The concept does not guarantee lossless conversion: agreement between the two conversion forms does not mean that the entire source value is preserved.
Examples
#include <concepts>
#include <iostream>
struct ExplicitOnly {
explicit operator int() const { return 7; }
};
template<class T>
requires std::convertible_to<T, int>
int as_int(T value) {
return static_cast<T&&>(value);
}
static_assert(std::convertible_to<short, int>);
static_assert(!std::convertible_to<ExplicitOnly, int>);
static_assert(requires(ExplicitOnly x) { static_cast<int>(x); });
int main() {
std::cout << as_int(short{7}) << '\n';
std::cout << static_cast<int>(ExplicitOnly{}) << '\n';
}
Result
7 7
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.