C++ 开启数据类型

标签 c++ enums boost-variant boost-any

我有一个 Attribute 类,它有一个指定属性类型的枚举(INT_64、UINT 64、INT_32、STRING、DOUBLE 等)。这个属性类使用 boost::any 来保存枚举指定类型的 vector 。

目前,为了处理这些数据,我有一个很大的 switch 语句,至少对于基本数据类型,我觉得会有更简单的方法。

我的 switch 语句看起来像这样:

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;
}

属性定义为:

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;
}

有没有办法避免 switch 语句,做类似的事情:

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

最佳答案

很遗憾,答案是否定的。正如 R Sahu 在评论中所说:

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.

关于C++ 开启数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25355646/

相关文章:

c++ - 接口(interface)的延迟实现

c++ - 将 boost::any 转换为 boost::variant 的通用函数

c++ - 这个访问者实现是否正确?

具有不变类型的每个元素的任何/变体的 C++ 容器

c++ - 使用 Visual C++ 和 MFC 发出 ping 声音错误

c++ - 未处理的异常 - C++ 程序在转换时停止

c++如何声明返回对象 vector 的函数

c - 类型定义一个枚举类型作为结构

带有标志枚举的 C# 设置

objective-c - 枚举数组 - 转换为 NSArray