FCF 2.0 development in progress...
> > > > > >
[News] [C++ Libraries API] [C++ Downloads] [Donate to the project] [Contacts]

cast() method from fcf::NTest::SharedPtrAny class

template <typename Ty>
Ty* cast()

Class: fcf::NTest::SharedPtrAny

Package: fcfTest

File: test.hpp

Available from version: 1.1.1

Attempts to cast the managed object to a specific type using runtime type information (RTTI).

The cast method provides a type-safe way to retrieve the underlying object from the fcf::NTest::SharedPtrAny container.

It uses Runtime Type Information (RTTI) to verify if the stored object matches the requested type. This is a non-throwing operation: if the types do not match, the method returns nullptr instead of throwing an exception, allowing for safe conditional access.

Template arguments
Ty - The target type to which the managed object should be cast.
Result
Ty*
- A pointer to the managed object of type Ty if the types match; otherwise, nullptr.

Example: Safe Type Casting

Demonstrates how to safely cast a managed object to its original type and how the method handles incorrect type requests.

#define FCF_TEST_IMPLEMENTATION #include <fcfTest/test.hpp> #include <string> #include <iostream> FCF_TEST_DECLARE("SharedPtrAny", "Demo", "CastExample"){ struct TargetType { std::string data; TargetType(std::string d) : data(d) {} }; // 1. Create a SharedPtrAny holding a TargetType object fcf::NTest::SharedPtrAny ptr = fcf::NTest::SharedPtrAny::make<TargetType>("Success"); // 2. Successful cast // We provide the correct type, so cast returns a valid pointer TargetType* validPtr = ptr.cast<TargetType>(); FCF_TEST(validPtr != nullptr, "Cast should succeed for the correct type"); FCF_TEST(validPtr->data == "Success", validPtr->data); // 3. Unsuccessful cast // We request an incorrect type (int), so cast returns nullptr int* invalidPtr = ptr.cast<int>(); FCF_TEST(invalidPtr == nullptr, "Cast should return nullptr for incorrect type"); // 4. Safe usage pattern if (TargetType* safePtr = ptr.cast<TargetType>()) { fcf::NTest::log() << "Retrieved data: " << safePtr->data << std::endl; } } int main(int a_argc, char* a_argv[]) { bool error = false; fcf::NTest::cmdRun(a_argc, a_argv, fcf::NTest::CRM_RUN, &error); return error ? 1 : 0; }

Output:

Performing the test: "SharedPtrAny" -> "Demo" -> "CastExample" ... > Retrieved data: Success [SUCCESS] Test completed successfully (0.000`007`960 sec) [SUCCESS] All tests were completed. Tests: 1 passed, 0 failed, 0 skipped, 1 total Duration: 0.000`007`960 sec