将构造函数作为回调参数或返回值传递

时间:2016-01-15 09:31:45

标签: c++ constructor callback

基本上我要做的就是上课:

class SomeClass {
    // Returns subclass of SomeClass by given name, or nullptr
    static SomeClass* childFromString(const std::string&);
}

我将使用if...else来查找实际的子类,其中有5个。但是为了推迟实例化,我想返回构造函数而不是refference:

class SomeClass {
    // This is an attempt to define "returns constructor of SomeClass"
    static (SomeClass)(int) childFromString(const std::string&);
}

将用作:

SomeClass* = new (SomeClass::childFromString("Child"))(someNumber);

这在C ++中看起来很奇怪,但在javascript或Java中是合法的。而且我认为它不需要反射才能工作,构造函数只是一个函数,对吧?

再一次,如何将构造函数函数作为参数传递或返回值?

3 个答案:

答案 0 :(得分:2)

由于

,无法调用构造函数,或返回构造函数或对其执行某些操作
  

构造函数没有名称。

你可以在函数中构造对象,或者向某个创建者返回一些函数指针。

答案 1 :(得分:2)

从C ++ 98 Standard 12.1 / 12构造函数:

  

不得采用构造函数的地址。

构造函数不是“正确”的函数。请注意,这同样适用于析构函数。

答案 2 :(得分:1)

您无法在C ++中将函数指针传递给构造函数。一种意识形态的方法是返回一个延迟构造的std ::函数:

struct ChildInterface {
     // your interface here
     virtual ~Interface() = default;

};

struct Paul : public Interface {
    // implementation of interface
};


std::function<Interface*()> getDeferedFactoryFor(const std::string& child)
{
     if (child == "paul") {
          return []() {
              return new Paul();
          };
     }
     if (child == "kara") {
          return []() {
              return new Kara();
          };
     }
     // more children here


     // error handling
     return []() {
          return nullptr;
     }
}

// usage example
void createChild()
{
    auto childCreator = getDeferedFactoryFor("paul");
    ChildInterface * paul = childCreator();
    paul->doSomeThing();
}
相关问题