首页 > 解决方案 > 如何使类的构造函数根据参数访问重载函数?

问题描述

我有以下场景:该类internalEntity应该以许多不同的形式(例如,等)存储boolCloud数据std::vector<TRIANGLE>。创建此对象时,构造函数应该initEntity()根据参数调用正确的函数。如何在不重载构造函数和函数的情况下做到这一点?

例如执行时

internalEntity myEntity(bCloud, "My bool Cloud");

其中bCloudboolCloud我想要initEntity()调用的第一个函数。

此示例不起作用,但该typename T部分应该说明我想要做什么。

class internalEntity
{
public:
    internalEntity(typename T, std::string name) { initEntity(T, name); };

    void initEntity(boolCloud& bCloud, std::string name);
    void initEntity(std::vector<TRIANGLE>& triMesh, std::string name);
    void initEntity(std::vector<dvec>& pointCloud , std::string name);

    void deleteEntity();

    //...


};

标签: c++overloading

解决方案


这种情况的一个常见解决方案是使用助手类的帮助:

template<typename T> struct initialize_me;

class internalEntity
{
public:
    internalEntity(typename T, std::string name)
    {
        initialize_me<T>::please(*this, name };

// ... The rest of the class declaration.

这个前向声明允许您在处理手头的业务之前定义类的其余部分。到那时,这变成了一个简单的专业化案例:

template<> struct initialize_me<bool> {

    inline static void please(internalEntity *me, const std::string &name)
    {
          boolCloud whatever_this_is;

          me->initEntity(whatever_this_is, name);
    }
};

对于所有其他必要的专业也是如此。从您的问题中不清楚重载initEntitys 的第一个参数来自哪里。如果它们是同一类的成员me,通常可以通过指针将它们传递到此处。如有必要,为了加强访问,助手类可以是一个friend.

如果必须在构造函数的初始化部分进行初始化,并且不能像在这种情况下那样推迟到主体,那就有点冒险了。然后,解决方案将取决于确切的细节,并且在找出解决方案之前将需要一个具体的具体示例。


推荐阅读