如何使模板函数的所有实例成为类的朋友

How to make all instances of a template function friends of a class?

本文关键字:朋友 实例 何使模 函数      更新时间:2023-10-16

我有一个类,它只能由一些工厂函数构造,而不是直接构造。

这些工厂函数都有相同的名称,但根据作为其模板参数传递的enum值进行区分(参见本答案中解释的第一个方法)。

这些函数的例子:

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) {...}

如何使所有这些函数同时成为类的朋友,以便它们可以使用类的私有构造函数?

。在上面的例子中,我希望Factory<foo>, Factory<bar>Factory<tag3>都可以访问myClass的私有成员,但我不想列出每个成员。我该怎么做呢?

使函数模板或类模板成为类的朋友:

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.