我有一个类模板 Obj
和一个函数模板 make_obj
.Obj
定义了一个 private
单个构造函数,该构造函数接受对其要绑定到的模板化类型的引用.
I have a class template Obj
and a function template make_obj
. Obj
has a private
single constructor defined, which takes a reference to its templated type to bind to.
template <typename T>
class Obj {
private:
T& t;
Obj(T& t)
: t{t}
{ }
};
template <typename T>
Obj<T> make_obj(T& t) {
return {t};
}
我想要的是将 make_obj
函数声明为 friend
以便它可以创建 Obj
的,但没有其他人可以(除了通过复制构造函数).
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&);
和
template <typename T1, typename T2>
friend Obj<T1> make_obj(T2&);
后者是对 Obj
类的 make_obj
朋友的所有模板实例化的不太理想的尝试.但是,在这两种情况下,我都会遇到相同的错误:
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<char const[6]>'
return {t};
^
note: in instantiation of function template specialization
'make_obj<const char *>' requested here
auto s = make_obj("hello");
^
尝试做 make_obj("hello");
用于示例目的.
trying to do make_obj("hello");
for example purposes.
如何只允许 make_obj
访问 Obj
的值构造器?
How can I allow only make_obj
access to Obj
's value contructor?
你需要一些前置声明:
template <typename T>
class Obj;
template <typename T>
Obj<T> make_obj(T t);
template <typename T>
class Obj {
private:
T & t;
Obj (T & t) : t(t) { }
Obj() = delete;
friend Obj make_obj<T>(T t);
};
template <typename T>
Obj<T> make_obj(T t) {
return Obj<T>(t);
}
实例
顺便说一句:我不认为你真的想要 T &t;
用于您的类的成员变量.可能 T t;
是更好的选择 ;)
And BTW: I don't think you really want T & t;
for your class' member variable. Probably T t;
is a better choice ;)
这篇关于声明模板类的模板友元函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!