How can I call a private template constructor from another template instance

eg:

template<class T>
class MyClass
{
public:
    template<class U>
    MyClass<U> doSomething() { return MyClass<U>(); } //can't access private constructor
private:
    MyClass() {}
}

      

Voodoo template responses and the like are acceptable. The most important thing for me is that this class can create and return instances of itself with different template parameters, but this external code cannot call the specific constructor it uses.

+3


source to share


2 answers


Add to MyClass

following:
template<typename Q> friend class MyClass;

      



MyClass<int>

and MyClass<float>

allow completely different classes. They don't know anything about each other and they can't access every other, no more than 2 completely different classes. So the solution is for each instance of the MyClass

friend to add all the other instances to each other so that they can see everyone else as if they were the same class.

+4


source


friend

is your friend in this case, since every time you need limited privacy exceptions:



class MyClass {
     template <class U> friend class MyClass;
     ....

      

+1


source







All Articles