3

在探索 C++ 中基于策略的设计模式时,我偶然发现了一个我找不到解决方案的问题:如何在不引用策略类中的成员变量的情况下以通用方式为基于策略的类编写复制和移动构造函数?

这是一个例子:

class Foobase {
public:
  Foobase(int v) :val(v) { }
protected:
  int val;
};

template <typename Base>
class Foo : public Base {
public:
  Foo(int v):Base(v) { }
  // how can I initialize Base() class without referring to it's protected members?
  Foo(const Foo<Base>& other) :Base(other.val) { }
};

int main() {
  Foo<Foobase> foo(5);
  auto foo2 = foo;
}

在上面的代码中,复制构造函数class Foo使用受保护的成员变量来初始化Base类。Base除了上述之外,还有其他方法可以初始化吗?在这种情况下,最佳做法是什么?

更新的问题:

@LogicStuff 的回答澄清了问题的复制构造函数部分,但没有回答移动构造函数问题。请参阅更新的示例代码,其中class Foo也可以包含成员变量。

class Foobase {
public:
  Foobase(int v) :val(v) { }
  Foobase(const Foobase&) = default;
  Foobase(Foobase&&) noexcept = default;
  Foobase& operator= (const Foobase&) = default;
  Foobase& operator= (Foobase&&) noexcept = default;
  void Print() const {
    std::cout << val << std::endl;
  }
protected:
  int val;
};

template <typename Base>
class Foo : public Base {
public:
  // works fine
  Foo(std::string str, int v):Base(v), name(str) { }

  // works fine
  Foo(const Foo<Base>& other) :Base(other), name(other.name) { }

  // I'm doubtful about this c'tor, if I move `other` for initializing Base,
  // how can I initialize `name` variable?
  Foo(Foo<Base>&& other)
    :Base(std::move(other)), name(std::move(other.name) /* will this be valid?? */) { }

  // can we have copy and assignment operator for this class?

  void Print() {
    std::cout << "name = " << name << std::endl;
    Base::Print();
  }

private:
  std::string name;
};

int main() {
  Foo<Foobase> foo("foo", 5);
  auto foo2 = std::move(foo);
  foo2.Print();
}
4

1 回答 1

2

您可以简单地使用Base的复制构造函数:

Foo(const Foo<Base>& other) : Base(other) { }

或者根本不定义它并留给编译器,如果你不打算在那里做额外的事情。

实际上,它可能看起来像这样,您的示例仍将编译:

template <typename Base>
class Foo : public Base {
public:
  using Base::Base;
};

编辑后:

现在您必须补充一个带有两个参数的构造函数(就像您所做的那样):

template <typename Base>
class Foo : public Base {
public:
  Foo(std::string str, int v) : Base(v), name(str) { }

  void Print() {
    std::cout << "name = " << name << std::endl;
    Base::Print();
  }

private:
  std::string name;
};

但是您还定义了由编译器生成的特殊成员函数(这意味着它们是正确的)。您的原始示例也是如此。两个版本Foo都是可移动构造的。

于 2017-09-01T18:52:45.890 回答