Can I use dynamic_cast conversion with proxy? #194
-
Can I use |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
@xuruilong100 Thanks for asking. However, it can be implemented with custom reflection if you really need. For example: #include <iostream>
#include <typeinfo>
#include "proxy.h"
class RttiReflector {
public:
template <class T>
constexpr explicit RttiReflector(std::in_place_type_t<T>) : type_(typeid(T)) {}
template <class F, class R>
struct accessor {
const std::type_info& GetType() const noexcept {
const RttiReflector& self = pro::proxy_reflect<R>(pro::access_proxy<F>(*this));
return self.type_;
}
};
private:
const std::type_info& type_;
};
struct Castable : pro::facade_builder
::add_convention<pro::operator_dispatch<"&">, void*() noexcept>
::add_reflection<RttiReflector>
::build {};
template <class T, class F>
T* proxy_cast(pro::proxy<F>& p) {
return p->GetType() == typeid(T) ? static_cast<T*>(&*p) : nullptr;
}
struct Stringable : pro::facade_builder
::add_facade<Castable>
::add_convention<pro::operator_dispatch<"<<", true>, std::ostream&(std::ostream&) const>
::build {};
int main() {
int v = 123;
pro::proxy<Stringable> p = &v;
std::cout << *p << "\n"; // prints: "123"
double* pd = proxy_cast<double>(p);
std::cout << std::boolalpha << (pd != nullptr) << "\n"; // prints: "false"
int* pi = proxy_cast<int>(p);
std::cout << (pi != nullptr) << "\n"; // prints: "true"
v = 456;
std::cout << *pi << "\n"; // prints: "456"
} Note that the code above uses some accessibility features in the upcoming 3.1 release. To compile it, you need to download the latest |
Beta Was this translation helpful? Give feedback.
@xuruilong100 Thanks for asking.
dynamic_cast
is not directly supported byproxy
. Although it might be useful in debugging, using it in production code is usually considered a bad practice (see some interesting discussions here). Therefore, we decided not to prioritize this feature over performance by default.However, it can be implemented with custom reflection if you really need. For example: