I am using RTTR library to write a general logger class. To have a simple log function, I am holding instance
at the class member. So far, it works when the instance is a class. But I cannot achieve converting basic types to string.
#include <iostream>
#include <string>
#include <rttr/registration>
struct MyStruct {
int my_int;
double my_double;
std::string my_string;
};
RTTR_REGISTRATION {
rttr::registration::class_<MyStruct>("MyStruct")
.property("my_int", &MyStruct::my_int)
.property("my_double", &MyStruct::my_double)
.property("my_string", &MyStruct::my_string)
;
} // RTTR_REGISTRATION
class RttrPrinter {
public:
RttrPrinter(rttr::instance instance)
: instance(instance)
{
}
void print_struct() const
{
for (const rttr::property& property : instance.get_type().get_properties()) {
const rttr::variant variant = property.get_value(instance);
std::cout << " " << variant.to_string();
}
std::cout << std::endl;
}
void print_basic_type() const
{
if (const std::string* ptr = instance.try_convert<std::string>()) {
std::cout << *ptr;
}
std::cout << std::endl;
}
private:
rttr::instance instance;
};
int main()
{
MyStruct my_struct {
.my_int = 1,
.my_double = 2.5,
.my_string = "three",
};
int global_int = 5;
RttrPrinter struct_printer(my_struct);
RttrPrinter basic_type_printer(global_int);
struct_printer.print_struct();
basic_type_printer.print_basic_type();
my_struct = MyStruct {
.my_int = 11,
.my_double = 12.5,
.my_string = "thirteen",
};
global_int = 15;
struct_printer.print_struct();
basic_type_printer.print_basic_type();
}
Output:
1 2.5 three
11 12.5 thirteen
The following code gives a compile time error.
rttr::variant variant = instance;
rttr/detail/impl/argument_impl.h(65,19): static_assert failed: ‘Don’t use the argument class for forwarding an instance!’
It seems I need to use variant::to_string
for successful conversions. Is there a way to create variant
from instance
without explicitly checking for all basic types?