基本クラスから継承するクラスごとにコピーコンストラクターを定義するようにプログラマーに強制できますか?基本クラスはインスタンス化できます。
私が持っている場合を意味します
class A {
public
A(const A&);
};
class B : public A {
public
B(const B&); // I want to force my programmers to write this line, any idea????
};
基本クラスから継承するクラスごとにコピーコンストラクターを定義するようにプログラマーに強制できますか?基本クラスはインスタンス化できます。
私が持っている場合を意味します
class A {
public
A(const A&);
};
class B : public A {
public
B(const B&); // I want to force my programmers to write this line, any idea????
};
おそらく答えはCRTPにあります。
私が今理解できる最も近い解決策は、疑似ベースと、プログラマーに思い出させるためのプライベート抽象 copy_construct 関数を備えた CRTP です。
template <class Derived>
class Base {
private:
virtual void copy_construct(const Derived& d) = 0;
//btw; unfortunately this isn't possible:
//virtual Derived(const Derived& b) = 0;
};
class PseudoBase : public Base<PseudoBase>
{
public:
PseudoBase() {};
PseudoBase(const PseudoBase& pd)
{
copy_construct(pd);
}
private:
void copy_construct(const PseudoBase& rhs)
{
//copy code
}
};
class Derived : public Base<Derived>
{
//Programmer forgot about copy constructing
};
int _tmain(int argc, _TCHAR* argv[])
{
PseudoBase pb0;
PseudoBase pb1 = pb0;
Derived d0;
Derived d1 = d0;
return 0;
}
ビルドは失敗します:
1>d:\source\test\test\test\test.cpp(42): error C2259: 'Derived' : cannot instantiate abstract class
1> due to following members:
1> 'void Base<Derived>::copy_construct(const Derived &)' : is abstract
1> with
1> [
1> Derived=Derived
1> ]
1> d:\source\test\test\test\test.cpp(9) : see declaration of 'Base<Derived>::copy_construct'
1> with
1> [
1> Derived=Derived
1> ]
バグとランタイムのクラッシュにより、開発者はその行を書かざるを得なくなると強く感じています