我有使用这种设计的代码,简化以获得这个 MCVE - 代码和编译器错误如下。
基本问题是我认为与 CRTP 类交朋友将允许模板化基类访问派生 CRTP 类的私有成员,包括其私有构造函数。
但显然它没有。为什么?
#include <iostream>
using namespace std;
template <class CRTP>
class Base
{
friend CRTP;
public:
static void Factory()
{
cout << "Base::Factory()" << endl;
CRTP x;
x.Hello();
}
virtual void Hello() { cout << "Base::Hello()" << endl; }
protected:
Base() { cout << "Base::Base()" << endl; }
virtual ~Base() { cout << "Base::~Base()" << endl; }
};
class Derived final : public Base<Derived>
{
public:
void Hello() override;
private:
Derived() { cout << "Derived::Derived()" << endl; }
~Derived() override { cout << "Derived::~Derived()" << endl; }
};
int main()
{
Derived::Factory();
// Expected output:
// Base::Factory()
// Base::Base()
// Derived::Derived()
// Derived::Hello()
// Derived::~Derived()
// Base::~Base()
}
并得到这个编译器错误(来自 clang 9.0.0,但 gcc 以同样的方式抱怨):
prog.cc:12:12: error: calling a private constructor of class 'Derived'
CRTP x;
^
prog.cc:33:14: note: in instantiation of member function 'Base<Derived>::Factory' requested here
Derived::Factory();
^
prog.cc:27:3: note: declared private here
Derived() { cout << "Derived::Derived()" << endl; }
^
prog.cc:12:12: error: variable of type 'Derived' has private destructor
CRTP x;
^
prog.cc:28:11: note: declared private here
virtual ~Derived() { cout << "Derived::~Derived()" << endl; }
^
2 errors generated.
(仅供参考:用例是我希望模板基类通过静态工厂控制(CRTP)派生类实例的生命周期 - 包括构造。所以我希望派生类将其构造函数声明为私有,但父类的静态可访问工厂方法。此示例显示了在堆栈上创建的派生类实例,但如果在堆中创建(并返回)也会发生相同的错误。)