Search code examples
c++enumsboost-variantboost-any

C++ Switch on Data Type


I have an Attribute class that has an Enum specifying the type of the attribute (INT_64, UINT 64, INT_32, STRING, DOUBLE, etc.). This Attribute class uses boost::any to hold a vector of the types specified by the enum.

At the moment in order to work with this data I have a big switch statement, and at least for the fundamental data types I feel like there would be an easier way to do it.

My switch statement looks something like this:

switch(attribute.type) {
    case DOUBLE:
        stmt->setNumber(col_counter, Number(attribute.get_value<double>(row_counter)));
        break;
    case INT_32:
        stmt->setNumber(col_counter, Number(attribute.get_value<int_32t>(row_counter)));
        break;
}

Attribute is defined as:

class Attribute
{
    public:
        template <typename T>
        T get_value(const unsigned index) const
        {
            const std::vector<T> * v = boost::any_cast<const std::vector<T> >(&data);
            return v->at(index);
        }

        Data_Type_Enum type;
        std::string name;
        boost::any data;
}

Is there a way of avoiding the switch statement, doing something similar to:

stmt->setNumber(col_counter, Number(attribute.get_value<attribute.type>(row_counter)));

Solution

  • Well, unfortunately the answer is no. As said by R Sahu in a comment:

    Not the way you want to. If get_value is a function template, you can use get_value only if attribute.type is a known integral constant at compile time.