I have a class that represents a cell in a grid (e.g., spreadsheet). The cell can be of variable type (only known at runtime):
- String (stored as a
std::string
) - Number (stored as a
double
) - DateTime (stored as a
QDateTime
using Qt library)
I formerly had three constructors, each taking a string representing the type and value (one constructor for each type, respectively), and I had separate variables for each type and a variable to store the type. Then I discovered std::variant
and it seems like the perfect tool for the job.
However, I'm confused about how to communicate type information to users of the class without them having to understand the index of the variant nor handle a bad_variant_access
exception. The method I came up with seems redundant as it involves a switch
statement to return a string representation of the type based on the variant index. Ideally they have no direct access to the variant variable itself.
Ideally I can write a template method that returns the correct type so the user of the class can use auto
to receive the value by calling this method, but the type isn't known until runtime. Would a template method still help me by saving typing (three overloaded methods—one for each type), or am I better with the overloaded methods given the type can't be deduced at compile time?
Is there any good design pattern for reducing redundancy while communicating type information and the value to the consumer of this class? Or am I better off not using a class and just using the variant directly in another data structure (e.g., storing the variant in a vector)?
Aucun commentaire:
Enregistrer un commentaire