a friend to instanciate a base class with private ctor

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.
 
N

nguillot

the last code snippet is:
template <class TtoBeFriend>
class X
{
friend TtoBeFriend; // or whatelse?
 
N

nguillot

I answer my last question.

We can define a template arg as a class friend of antoher class with
this "indirection":

#include "loki/TypeManip.h"

template <typename T>
class X
{
friend class Loki::Type2Type<T>::OriginalType;
};

where Loki::Type2Type is:

template <typename T>
struct Type2Type
{
typedef T OriginalType;
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,709
Latest member
AustinMudi

Latest Threads

Top