【问题标题】:How can I make the constructor of a class access an overloaded function based on the argument?如何使类的构造函数根据参数访问重载函数?
【发布时间】:2020-03-29 22:55:46
【问题描述】:

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

例如执行时

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

其中 bCloud 是 boolCloud 我希望调用第一个 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


    【解决方案1】:

    这种情况的常见解决方案是借助辅助类:

    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。

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

    【讨论】:

      猜你喜欢
      • 2015-11-05
      • 2012-11-30
      • 2021-09-14
      • 2018-06-23
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多