templated friend function of templated class with private constructor
I have a templated class Obj and a make_obj function. Obj has a single
constructor defined, which takes a reference to it's templated type to
bind to.
template <typename T>
class Obj {
private:
T & t;
Obj (T & t) : t(t) { }
Obj() = delete;
};
template <typename T>
Obj<T> make_obj(T t) {
return Obj<T>(t);
}
As you can see, this constructor is private. What I want is to declare the
make_obj function a friend so that it can create Obj's, but no one else
can (except via the copy ctor).
I have tried several friend declaration including
friend Obj make_obj(T &);
and
template <typename T1, typename T2>
friend Obj<T1> make_obj(T2 &);
The latter being a less than desirable attempt at making all template
instantiations of make_obj friends of the Obj class. However in both of
these cases I get the same error:
error: calling a private constructor of class
'Obj<const char *>'
return Obj<T>(t);
^
note: in instantiation of function template specialization
'make_obj<const char *>' requested here
auto s = make_obj("hello");
^
trying to do make_obj("hello"); for example purposes.
How can I allow only make_obj access to Obj's value contructor?
No comments:
Post a Comment