问题描述
我具有以下模板类和模板函数,旨在访问该类的私有数据成员:
I have the following template class and template function which intends to access the class' private data member:
#include <iostream>
template<class T>
class MyVar
{
int x;
};
template<class T>
void printVar(const MyVar<T>& var)
{
std::cout << var.x << std::endl;
}
template<class T>
void scanVar(MyVar<T>& var)
{
std::cin >> var.x;
}
struct Foo {};
int main(void)
{
MyVar<Foo> a;
scanVar(a);
printVar(a);
return 0;
}
要将两个函数声明为MyVar<T>
的朋友函数,我尝试了在template<class T> class MyVar
声明中声明友谊的以下方法.它们都不起作用.我该怎么办?
To declare the two functions as MyVar<T>
's friend functions, I've tried the following ways inside the declaration of template<class T> class MyVar
to declare friendship. None of them works. How should I do?
template<class T> friend void printVar(const MyVar&);
template<class T> friend void scanVar(MyVar&);
// compilation error
template<class T> friend void printVar(const MyVar<T>&);
template<class T> friend void scanVar(MyVar<T>&);
// compilation error
friend void printVar(const MyVar<T>&);
friend void scanVar(MyVar<T>&);
// link error
friend void printVar(const MyVar&);
friend void scanVar(MyVar&);
// link error too
推荐答案
最简单的选择是在类中定义朋友:
The simplest option is to define the friend within the class:
template<class T>
class MyVar
{
int x;
friend void printVar(const MyVar & var) {
std::cout << var.x << std::endl;
}
friend void scanVar(MyVar & var) {
std::cin >> var.x;
}
};
缺点是只能通过依赖于参数的查找来调用函数.在您的示例中这不是问题,但是如果他们没有合适的参数,或者您想在不调用名称的情况下指定名称,则可能是一个问题.
The downside is that the functions can only be called through argument-dependent lookup. That's not a problem in your example, but might be a problem if they don't have a suitable argument, or you want to specify the name without calling it.
如果要使用单独的定义,则必须在类定义之前声明模板(以便可用于朋友声明),然后在之后定义(以便它可以访问类成员).该类也必须在函数之前声明.这有点混乱,所以我只显示两个功能之一:
If you want a separate definition, then the template will have to be declared before the class definition (so it's available for a friend declaration), but defined afterwards (so it can access the class members). The class will also have to be declared before the function. This is a bit messy, so I'll only show one of the two functions:
template <typename T> class MyVar;
template <typename T> void printVar(const MyVar<T> & var);
template<class T>
class MyVar
{
int x;
friend void printVar<T>(const MyVar<T> & var);
};
template <typename T> void printVar(const MyVar<T> & var) {
std::cout << var.x << std::endl;
}
这篇关于模板类的模板朋友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!