I want do make some classes, which will have private/protected constructors, and will have static method named create().
Let me show you the code:
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;
}
Compiling with GCC 4.6.1, I am given the following error:
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
The main problem is that
ServiceCreator<T>::create()is going to try and instantiate S over here:But of course it cannot do that because
class S‘s constructor is protected! An easy way to fix this is to just make ServiceCreator a friend to S: