c++ - 如何使模板函数的所有实例成为类的 friend ?

标签 c++ c++11 templates friend-function

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

这些工厂函数都具有相同的名称,但根据作为模板参数传递的枚举值进行区分(参见 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/

相关文章:

c++ - 有双向管道之类的东西吗?我希望输入和输出在两个简单程序之间交互

c++ - uintptr_t 存储的是指针的地址还是它的值?

c++ - 在 const 函数中检查成员 std::array 的边界问题

稀疏矩阵实现的 C++11 兼容性

python - Django 找不到模板目录

c++ - 限制可变参数函数模板仅接受一个可变参数类模板的嵌套可变参数类模板的变体?

c++ - 将颜色数据渲染到窗口,Win32

c++ - std::this_thread::yield 只是一个提示会不会有问题?

c++ - 如果有人在 C++ 中调用方法,则强制错误(编译时)

c++ - 类型别名模板参数包