在探索 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();
}