我有一个类,它只能由一些工厂函数构造,而不是直接构造。
这些工厂函数都具有相同的名称,但根据作为模板参数传递的枚举值进行区分(参见 this answer 中解释的第一种方法)。
这些函数的一个例子:
enum Tag {
foo,
bar,
tag3
};
//declarations
template <Tag>
myClass Factory(int, char);
template <Tag>
myClass Factory(std::string, float);
//definitions
template <>
myClass Factory<foo>(int x, char y) {...}
template <>
myClass Factory<bar>(std::string x, float y) {...}
//as you can see, this way I can have functions with the same
//arguments that do different things with different tags:
template <>
myClass Factory<tag3>(int x, char y) {...}
如何让所有这些函数同时成为类的友元,以便它们可以使用它的私有(private)构造函数?
即在上面的示例中,我希望同时拥有 Factory<foo>
, Factory<bar>
和 Factory<tag3>
可以访问 myClass 的私有(private)成员,但我不想列出每个成员。我该怎么做?
最佳答案
让函数模板或类模板成为你的类的 friend :
template<class T>
class foo;
// forward declaration of the function. not really needed
template<class T>
void fun(T);
class myclass
{
private:
int a;
template<class T> friend class foo;
template<class T> friend void fun(T);
// the above line declares foo<T>(T) to be friend of myclass
};
// the specializations definitions follow below
template<> void fun<int>(int i)
{
myclass m;
m.a = i;
}
template<> void fun<char>(char c)
{
myclass m;
m.a = int(c);
}
// as you can see, they both can use the private members of myclass.
关于c++ - 如何使模板函数的所有实例成为类的 friend ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40428033/