N
nguillot
Hello.
I'm trying to forbid the instantiation of classes, except through a
function whose role it is.
I'm trying to do that by making the involved classes inherit from a
class whose ctor is private.
Something like that:
template <typename T>
T* create() { return new T(); }
class noninstanciable : protected boost::noncopyable
{
template <typename T>friend T* create();
// private ctor
noninstanciable() {}
};
class MyClass : noninstanciable
{
public:
MyClass() {}
}
int main()
{
MyClass * c = make<MyClass>();
}
But it doesn't work because of the private noninstanciable ctor.
So I tried to make make<MyClass> as friend of noninstanciable like
that:
template <typename T>
class noninstanciable : protected boost::noncopyable
{
friend T* create<T>();
// private ctor
noninstanciable() {}
};
class MyClass : noninstanciable<MyClass> { /* ... */ };
But same issue.
Finally I tried to make MyClass as a friend of noninstanciable (but if
I succeeded MyClass would be directly instanciable...) like that:
template <typename T>
class noninstanciable : protected boost::noncopyable
{
friend typename T; // or also friend T or also friend class T
// private ctor
noninstanciable() {}
};
but it doesn't compile.
So 2 questions:
1) do you see a way to achieve what I try?
2) how to make a template argument type of a class a friend of this
class, ie:
template <class TtoBeFriend>
class X
{
friend X; // or whatelse?
}
Thanks for reply.
I'm trying to forbid the instantiation of classes, except through a
function whose role it is.
I'm trying to do that by making the involved classes inherit from a
class whose ctor is private.
Something like that:
template <typename T>
T* create() { return new T(); }
class noninstanciable : protected boost::noncopyable
{
template <typename T>friend T* create();
// private ctor
noninstanciable() {}
};
class MyClass : noninstanciable
{
public:
MyClass() {}
}
int main()
{
MyClass * c = make<MyClass>();
}
But it doesn't work because of the private noninstanciable ctor.
So I tried to make make<MyClass> as friend of noninstanciable like
that:
template <typename T>
class noninstanciable : protected boost::noncopyable
{
friend T* create<T>();
// private ctor
noninstanciable() {}
};
class MyClass : noninstanciable<MyClass> { /* ... */ };
But same issue.
Finally I tried to make MyClass as a friend of noninstanciable (but if
I succeeded MyClass would be directly instanciable...) like that:
template <typename T>
class noninstanciable : protected boost::noncopyable
{
friend typename T; // or also friend T or also friend class T
// private ctor
noninstanciable() {}
};
but it doesn't compile.
So 2 questions:
1) do you see a way to achieve what I try?
2) how to make a template argument type of a class a friend of this
class, ie:
template <class TtoBeFriend>
class X
{
friend X; // or whatelse?
}
Thanks for reply.