我想创建一些类,它们将具有私有(private)/ protected 构造函数,并将具有名为 create()
的静态方法。
让我向您展示代码:
template <class T>
struct ServicePtr
{
std::shared_ptr<T> service;
};
template <class T>
struct ServicePtrDeleter
{
void operator()(T* ref) const
{
if (ref->service.get())
{
}
delete ref;
}
};
template <typename T>
struct ServiceCreator
{
static std::shared_ptr< ServicePtr<T> > create()
{
std::shared_ptr< ServicePtr<T> > servicePtr(new ServicePtr<T>);
servicePtr->service.reset(new T);
return servicePtr;
}
};
class S:public IService,
public ServiceCreator<S>
{
protected:
S()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
public:
virtual ~S()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
auto s=S::create();
return 0;
}
使用 GCC 4.6.1 编译,出现以下错误:
main.cc: In static member function 'static std::shared_ptr > ServiceCreator::create() [with T = S]':
main.cc:310:12: instantiated from here
main.cc:275:3: error: 'S::S()' is protected
main.cc:177:3: error: within this context
make: * [main.o] Error 1
最佳答案
在 ServiceCreator::create()
中,您这样做:
servicePtr->service.reset(new T);
如果 T
是 S
,这会尝试创建一个 S
,但会失败,因为 S
有一个 protected 构造函数。要允许不相关的类访问该构造函数,同时保护它,您必须将创建者类(或仅需要访问的成员函数)作为 friend :
friend ServiceCreator<S>::create;
关于c++ - 使用静态方法(又名工厂)派生类,使用 Base 类进行模板化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9033741/