Given several data types, I'm trying to implement a method to determine which type can be converted to by all other types.
Int -> Float -> Boolean
A int can be converted to a float which can converted to a boolean. However this is not the case for the other way round, e.g. a boolean cannot be converted to a float.
So given that I have the following types: int, float, boolean, the type that can be converted to by all other types is a boolean. This can be figured out using the following table where all the types in the problem are compared against one another to determine if they can be converted to it:
int | float | boolean | |
---|---|---|---|
int | true | true | true |
float | false | true | true |
boolean | false | false | true |
e.g. in the int row, a int can be converted to a int, float and boolean. However in the float row, a float cannot be converted to a int, but can be converted to a float or boolean.
The boolean column is all true, showing that all other types can be converted to it.
I'm trying to implement this logic into C++ however I'm having trouble determining the best kind of container for the table in terms of performance. I already have a method called canConvert(Type1, Type2)
which returns true/false if Type1
can be converted to Type2
, which will be used to populate the table. The table will require lookups via both row and column, and also require a scan at the end column by column to determine if all of the column's rows are true.
What would be the best kind of container to support such this kind of comparison?
There is std::is_convertible
, but I think your table doesnt match the definition of std::is_convertible
(eg std::is_convertible<int,float>::value
and std::is_convertible<float,int>::value
are both true
).
Nevertheless, your table only depends on types, hence there is no need to make the table occupy memory. You can encode the information in types:
template <typename T,typename U>
struct my_table : std::false_type {};
I chose to make false
the default, so that you only need to specialize for the true
cases:
template <> struct my_table<bool,int> : std::true_type {};
template <> struct my_table<bool,float> : std::true_type {};
template <> struct my_table<bool,bool> : std::true_type {};
// ...