| 30 | namespace { |
| 31 | |
| 32 | void ExampleAny() { |
| 33 | namespace ffi = tvm::ffi; |
| 34 | // Create an Any from various types |
| 35 | ffi::Any int_value = 42; |
| 36 | ffi::Any float_value = 3.14; |
| 37 | ffi::Any string_value = "hello world"; |
| 38 | |
| 39 | // AnyView provides a lightweight view without ownership |
| 40 | ffi::AnyView view = int_value; |
| 41 | // we can cast Any/AnyView to a specific type |
| 42 | int extracted = view.cast<int>(); |
| 43 | EXPECT_EQ(extracted, 42); |
| 44 | |
| 45 | // If we are not sure about the type |
| 46 | // we can use as to get an optional value |
| 47 | std::optional<int> maybe_int = view.as<int>(); |
| 48 | if (maybe_int.has_value()) { |
| 49 | EXPECT_EQ(maybe_int.value(), 42); |
| 50 | } |
| 51 | // Try cast is another version that will try to run the type |
| 52 | // conversion even if the type does not exactly match |
| 53 | std::optional<int> maybe_int_try = view.try_cast<int>(); |
| 54 | if (maybe_int_try.has_value()) { |
| 55 | EXPECT_EQ(maybe_int_try.value(), 42); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | TEST(Example, Any) { ExampleAny(); } |
| 60 | |