xtd 0.2.0
as.cpp

Shows how to use xtd::as operator.

#include <xtd/as>
#include <xtd/console>
#include <xtd/convert>
#include <xtd/convert_pointer>
#include <xtd/random>
using namespace xtd;
auto main() -> int {
double d = 41.6;
int i1 = convert::to_int32(d);
int i2 = as<int>(d);
console::write_line("d = {0}, convert::to_int32(d) = {1}, as<int>(d) = {2}", d, i1, i2);
int i = 42;
string s1 = convert::to_string(i);
string s2 = as<string>(i);
console::write_line("i = {0}, convert::to_string(i) = {1}, as<string>(i) = {2}", i, s1, s2);
std::any a = "string";
s2 = as<string>(a);
console::write_line("a = {0}, convert::to_string(a) = {1}, as<string>(a) = {2}", a, s1, s2);
console::write_line("p = {0}, convert_pointer::to_ptr<string>(p) = {1}, as<string>(p) = {2}", *p, *p1, *p2);
try {
console::write_line("as<string>(rand) = {0}", as<string>(rand));
} catch (const invalid_cast_exception& e) {
console::write_line("Bad cast : {0} !", e.message());
}
ptr<object> ver = new_ptr<version>(1, 1, 5);
try {
ptr<string> str = as<string>(ver);
} catch (const invalid_cast_exception& e) {
console::write_line("Bad cast : {0} !", e.message());
}
}
// This code produces the following output :
//
// d = 41.6, convert::to_int32(d) = 42, as<int>(d) = 42
// i = 42, convert::to_string(i) = 42, as<string>(i) = 42
// a = string, convert::to_string(a) = string, as<string>(a) = string
// p = a, convert_pointer::to_ptr<string>(p) = a, as<string>(p) = a
// Bad cast : std::bad_cast !
// Bad cast : std::bad_cast !
static void write_line()
Writes the current line terminator to the standard output stream using the specified format informati...
static int32 to_int32(std::any value)
Convert std::any to int32.
static string to_string(std::any value)
Convert std::any to string.
The exception that is thrown for invalid casting or explicit conversion.
Definition invalid_cast_exception.hpp:19
Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet c...
Definition random.hpp:43
xtd::sptr< type_t > ptr
The xtd::ptr object is a shared pointer.
Definition ptr.hpp:27
static const new_type_t * to_ptr(const current_type_t *value)
Casts a type into another type.
Definition convert_pointer.hpp:46
ptr< type_t > new_ptr(args_t &&... args)
The xtd::new_ptr operator creates a xtd::ptr object.
Definition new_ptr.hpp:24
type_t as(any_object &o)
Casts a type into another type.
Definition __as_any_object.hpp:59
@ a
The A key.
Definition console_key.hpp:88
@ d
The D key.
Definition console_key.hpp:94
@ p
The P key.
Definition console_key.hpp:118
@ i
The I key.
Definition console_key.hpp:104
@ e
The E key.
Definition console_key.hpp:96
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition abstract_object.hpp:8