【问题标题】:Multi Typed Data Class c++多类型数据类 c++
【发布时间】:2015-04-13 07:13:20
【问题描述】:

我的问题如下:

我需要创建一个支持以下代码的A类:

class B{
   //some composed type
}

A a;
a.setValue(1);
a.setValue(2.2);
a.setValue('c');
a.setValue(B());

关键是我需要一个实例来保存设置的值,并且只有它。这意味着我需要一个包含数据的变量,或者指向数据的变量,但 A 不知道该类型,将来可能会添加更多类型(例如 B)。

重载并不能解决这个问题,因为如果类型是 int 而不是 double,值将保存在哪里? 模板不能解决这个问题,因为对a.setValue(...) 的调用必须与上述完全一样,没有模板需要的“”字符。

我还通过定义尝试了隐式强制:

class MyObj{
   MyObj* theObj;
   MyObj(){}
   virtual ~MyObj() = 0;//with later empty implementation
   setValue(myObj* newVal){theObj = newVal;}
}
class MyInt:MyObj{
   myInt(){}
   myInt(int theInt){}//for implicit cast from int
}
a.setValue(1);

这会失败,因为编译器可以自动将 int 转换为 myInt,但 setValue 需要 myObj,所以即使强制可以工作,编译器也不会自动进行推导。

我该如何解决这个问题?

谢谢。

【问题讨论】:

标签: c++ type-conversion


【解决方案1】:

根据 ECS 设计模式,您可以执行以下操作:

struct BaseType {
    virtual ~BaseType() {}
};

template <typename T>
struct SpecializedType : public BaseType{
    SpecializedType(const T& v) : val(v) {}
    ~SpecializedType() {}
    T val;
};

class A {
    std::vector<std::unique_ptr<BaseType>> values;

public:
    template <typename T> void add(const T& val)
    {
        values.push_back(std::make_unique<SpecializedType<T>>(val));
    }

    template <typename T> T get()
    {
        for (auto& base : values)
        {
            auto* ptr = dynamic_cast<SpecializedType<T>*>(base.get());
            if (ptr)
                return ptr->val;
            }
            throw std::exception("no value found");
        }
    }
};

int main(void)
{
    A a;
    a.add(1.0f);
    a.add<std::string>("toto"); // You can specify the type when adding

    std::cout << a.get<float>() << std::endl;
    std::cout << a.get<std::string>() << std::endl;
    std::cout << a.get<int>() << std::endl; // Throws an exception because no int has been added
}

专业版:

  • 你可以添加任何你想要的类型

  • C++11/14 内存管理

缺点:

  • 每种类型只能有一个值

  • dynamic_cast

显然,您可以根据需要改进系统,即通过向值添加标识符以避免动态转换

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-12
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多