首页 > 解决方案 > 在传递对类的引用时优先使用重载函数,它实现了接口

问题描述

这就是我正在使用的(大致)

template<class t>
class Manager{
//this class has a internal map which you can use to store classes of 1 type with a key.
//This class is also a templated singelton (which means that you can call getInstance() for 
//any type like so: Manager<someType>::getInstance()
//...
public:
    void addComponent(int key, const t& newThing){
    //add to internal map
    }

    void addComponent(int key, AddsFriends<t>& newThing){
    //add newThing & Friends to map
    }
}

template<class t>
class AddsFriends<t>{
public:
   virtual void addFriends(int key){
   //add the Friend classes to the maps upon being called
   }
}

这是我想出的一个练习,所以它没有什么太合乎逻辑的东西。基本上,当我从任何类型获得 Manager 时,我应该能够使用指定的键和组件向它添加一个条目(它将在插入时复制。)我还可以使用 get 函数检索插入的类(上面未显示) .

当使用扩展“AddsFriends”的类型时,我希望能够使用键调用“addFriends”,以便可以将任何“Friend-instances”添加到多种类型中。这样我有点想做一些东西,我可以有一个名为“Person”的类,并让它在添加人时向具有相同 ID 的相应经理添加一个“Hat”类(因此插入的每个“人”也会导致“帽子”被插入)。我希望这是可以理解的。

但是,我无法确定此接口是否已实现。我尝试做 dynamic_cast 并检查异常,但这需要丢失 const-expression -> 使插入语句更长(因为我必须存储变量“just”以使其充当初始化程序,而不是仅仅调用add-function 中的构造函数)

我怎样才能让 c++ 在这里选择正确的函数?

编辑:

这是我打算如何使用管理器:

int key;
Manager<std::string>& stringManager = Manager<std::string>::getInstance();
stringManager.addComponent(key, "Hello there");

Manager<Foo>& fooManager = Manager<Foo>::getInstance();
fooManager.addComponent(key, Foo("Some init Params"));

class Foo: public AddsFriends<Foo>{
private:
    std::string *friendString = nullptr;
 //Other stuff
public:
    //Do constructor and whatever else you want
    virtual void addFriends(int key){
    //add the Friend classes to the maps upon being called
         Manager<std::string>& stringManager = Manager<std::string>::getInstance();
         stringManager.addComponent(key, "This belongs to the foo component!");
         //Note: The way I do this changed in my actual implementation, where I return a reference directly in the addComponent method. When I asked this question I was still using this function just because I didnt want to make the problem more complicated before I could get the old version to work. getNewest just return the reference to the newest component.
         this->friendString = &stringManager.getNewest();

    }

}

我希望以这种方式添加朋友的原因是,我可以通过组合拥有与其他组件使用相同功能的“组件”,但仍然可以通过适当的管理器访问他们使用的“组件”。假设我有一个名为“Cube”的组件和一个名为“Position”的组件。多维数据集包含表示多维数据集所需的数据,但它也有一个分配给它的位置。如果我只是使用“位置”属性进行常规合成,它会起作用,但位置不会像它应该那样在 PositionManager 中。这将导致一组不完整的托管组件,并且有点破坏首先拥有这些管理器的意义:/。

标签: c++

解决方案


我认为最简单的选择是专业化Manager

template <class t>
class Manager {
   public:
      void addComponent(int key, const t& newThing){
         //add to internal map
      }
};

template <class t>
class Manager<AddsFriends<t>> {
   public:
      void addComponent(int key, AddsFriends<t> const& newThing){
         //add newThing & Friends to map
      }
};

推荐阅读