如何使模板函数的所有实例成为类的朋友
How to make all instances of a template function friends of a class?
我有一个类,它只能由一些工厂函数构造,而不是直接构造。
这些工厂函数都有相同的名称,但根据作为其模板参数传递的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.
相关文章:
- 从C++实例化QML
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 建议在运行时将带有类实例的列表从c++导入qml
- 约束和显式模板实例化
- 限制多模板参数朋友函数可访问的类实例的范围
- 使类模板成为其自身的朋友,以进行不同的实例化
- 合格的朋友函数模板实例化
- 我如何将模板实例化为我班级的朋友
- 操作员的特定于朋友的模板实例化
- 如何使模板类的一个实例与同一模板的另一个实例成为朋友
- 如何使模板函数的所有实例成为类的朋友