【问题标题】:Storing data of any type in a vector ( Templates ) [duplicate]在向量中存储任何类型的数据(模板)[重复]
【发布时间】:2022-07-25 20:54:14
【问题描述】:

如果我有这样的结构:

template<typename t>
struct Data
{
    t* value;
}

我想将它存储在一个向量中以供运行时使用... 那我该怎么做呢?

这行不通:

std::vector<Data*> data;

我在网上阅读了许多指南,这些指南建议使用带有虚函数的基类.... 但是在这里我必须存储数据类型本身...

谢谢

【问题讨论】:

  • 你可以考虑std::any或者实现你自己的类型擦除类型。
  • 不要使用std::any,这对工作来说是错误的。你应该重新考虑为什么需要这个。
  • 然后创建一个接口(抽象基类,它也有利于测试,因为您也可以使用虚拟实现进行测试)。并创建一个指向这些接口的非拥有指针向量。
  • 你需要反过来想,注入动画信息而不是存储对象本身。
  • @KrishGanatra 如果用户只在动画中添加了位置更改,那么我将更改位置 -- Visitor pattern

标签: c++ oop templates polymorphism


【解决方案1】:

这是我试图在我的 cmets 中描述的代码: 每个动画对象可能有额外的信息来知道每个时间戳要做什么。

#include <vector>
#include <memory>

// Model information you need to pass on to your animations
struct AnimationData
{
    double time;
    // add more info if needed
};

// Define an interface for classes that can be animated
class AnimatableItf
{
public:
    virtual ~AnimatableItf() = default;
    virtual void animate(const AnimationData&) = 0;
};

// implement animations in a class specific way
class Texture :
    public AnimatableItf
{
public:
    void animate(const AnimationData& data) override
    {
        // do something with texture coordinates
    }
};

class Monster :
    public AnimatableItf
{
public:
    void animate(const AnimationData& data) override
    {
        // move and do whatever with your monster
    }
};

class Game
{
public: 
    // add animatables to the container
    Game() :
        m_animatables{ &m_monster, &m_texture }
    {
    }

    // loop over the container and call animate on all animatables
    void animate_all(const AnimationData& data) 
    {
        for (auto& animatable : m_animatables)
        {
            animatable->animate(data);
        }
    }

private:
    std::vector<AnimatableItf*> m_animatables;
    Monster m_monster;
    Texture m_texture;

};

int main()
{
    Game game;
    AnimationData data{ 0.001 };
    game.animate_all(data);

    return 0;
};

【讨论】:

    猜你喜欢
    • 2014-10-24
    • 2014-06-23
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    相关资源
    最近更新 更多