How to implement a class that dynamically switching types using std::variant in runtime?
I'm currently trying to create a class that can:
- Store a value in a
std::variantwith configurable type options (in my casedoubleandfloat) - Dynamically switch the active type at runtime using a
setType<T>()method - Be callable as a function to convert inputs to the currently active type
Here's my current attempt of implementation:
#include <variant>
#include <iostream>
#include <typeinfo>
class TypeAliasClass {
public:
TypeAliasClass() {
value = float(1);
}
template <typename T>
auto operator()(T transformable) {
return std::visit([&](const auto& active_value) {
using ActiveType = std::decay_t<decltype(active_value)>;
if (std::is_convertible_v<T, ActiveType>) {
return static_cast<ActiveType>(transformable);
} else {
std::cerr << "Couldn't convert given parameter to active type("
<< typeid(ActiveType).name() << ")\n";
return ActiveType{};
}
}, value);
}
template<typename T>
void setType() {
value = T(1);
}
~TypeAliasClass() {
std::cout << "Destroying TypeAliasClass with active type: "
<< std::visit([](auto&& arg) {
return typeid(arg).name();
}, value)
<< std::endl;
}
private:
std::variant<float, double, int> value; // int was included as an exmaple
};
Example Usage:
TypeAliasClass converter;
converter.setType<int>();
std::cout << converter(3.14) << "\n"; // Returns 3
converter.setType<double>();
std::cout << converter("69") << "\n"; // Error
std::variant<std::type_identity<Ts>...>seems more appropriate, as you don't store value.auto operator()cannot depend of runtime value (type stored in thevariant).ifshould beif constexprthough.converter(3.14)return two different types on different invocations. This is fundamental to C++.