[英]CRTP access to protected CTOR in derived
I've looked around on stackoverflow, and I don't see my precise issue, so I'm posting it. 我查看了stackoverflow,我没有看到我的确切问题,所以我发布了它。 I am building this with cxx03, so cxx11+ features are not permitted.
我用cxx03构建它,所以不允许使用cxx11 +功能。
I have the following simplified illustration: 我有以下简化的插图:
template<typename T>
struct unprotect : public T {
static T *create(void) {
return new T;
}
};
template<class T>
struct Base
{
private:
public:
static T * Create(void) {
return unprotect<T>::create();
}
static void Destroy(T *p) {
delete p;
}
};
struct Derived : public Base<Derived>
{
protected:
Derived(void){}
};
int main(int argc,const char** argv)
{
Derived * d = Derived::Create();
Derived::Destroy(d);
return( 0 );
}
And this produces the following error in g++ v4.8: 这会在g ++ v4.8中产生以下错误:
24)~/workspace/tricks $ g++ src/tricks.cpp
src/tricks.cpp: In instantiation of 'static T* unprotect<T>::create() [with T = Derived]':
src/tricks.cpp:14:37: required from 'static T* Base<T>::Create() [with T = Derived]':
src/tricks.cpp:29:28: required from here
src/tricks.cpp:24:5: error: 'Derived::Derived()' is protected
Derived(void){}
^
src/tricks.cpp:4:20: error: within this context
return new T;
I would have thought that, since unprotect inherits from T, the unprotect::create() would have access to the derived class' protected constructor. 我原以为,由于unprotect继承自T,unprotect :: create()可以访问派生类'protected constructor。
And that's the rub, really: Using CRTP, I want Base to be able to add a create() method that has access to the CTOR for Derived, but does not require Derived to claim friendship with Base. 真的很简单:使用CRTP,我希望Base能够添加一个create()方法,该方法可以访问衍生的CTOR,但不需要Derived声明与Base的友谊 。
A bad approach would be to do something like the following: 一个糟糕的方法是做类似以下的事情:
template<typename T>
struct unprotect : public T {
static T *create(void) {
return new unprotect;
}
};
This would get past the initial problem, but it would balk on (pure) virtuals, and very probably cause a nasty surprise or two. 这将超越最初的问题,但它会对(纯粹的)虚拟产品犹豫不决,并且很可能会导致一两个令人讨厌的惊喜。
Is there a way to make the original implementation work? 有没有办法让原始实现工作? Again, I do not want to add Base friendship to Derived.
同样,我不希望添加基地友谊派生。
Unfortunately in C++ you can't do what you're trying to do. 不幸的是,在C ++中你不能做你想做的事情。 You either have to write the public create function in
Derived
or allow its constructor to be public (what problem are you trying to solve with a protected constructor here?). 您要么必须在
Derived
编写公共创建函数,要么允许其构造函数是公共的(您在这里尝试用受保护的构造函数解决什么问题?)。
All that protected means is that a derived class's this
pointer can be used to access protected members of the parent class. 所有受保护的手段都是派生类的
this
指针可用于访问父类的受保护成员。 It doesn't grant a child class arbitrary access to arbitrary protected members of arbitrary parent class instances (including when the instance is just created by new
). 它不授予子类任意访问任意父类实例的任意受保护成员的权限(包括实例刚刚由
new
创建)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.