c++ - 友元函数声明中的尖括号是什么意思?

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

我很难理解符号 <>在作为 friend 的函数声明中。 (这是由于需要定义一个函数的主体而产生的,该函数是一个注入(inject)到外部自由函数中的友元。)

template<class T> class A;

template<class T> double f(A<T> const& a);

template<class T>
class A{
    double p_;
    friend double f<>(A<T> const& a); // same as friend double f<>(A const& a);
};

这是否完全等同于 friend double f<T>(A<T> const& a); ? 如果是这样,这个符号的目的是什么 <> ?毕竟f没有默认模板参数。

更普遍的情况是:

template<class T1, class T2, ...>
class A{
    double p_;
    friend double f<>(A const& a); // same as double f<T1, T2, ...>?
};

?

最佳答案

friend double f<T>(A<T> const&)相同.您通常会使用空模板参数来消除函数非模板 f 之间的歧义。和一个函数模板 f .如果你没有<>编译器会创建一个完全独立的非模板函数 f和另一个f<T>将无法访问私有(private)成员。

template<class T> class A;
template<class T> double f(A<T> const& a);
template<class T>
class A {
  double p_;
  friend double f(A<T> const& a); // notice omission of <>, declared as non-template
};

template<class T>
double f(A<T> const& a) {
  return a.p_;
}

int main() {
  f<>( A<int>{} ); // 'double A<int>::p_' is private within this context
}

Is is [sic] the case that more generally:

template<class T1, class T2, ...>
class A{
    double p_;
    friend double f<>(A const& a); // same as double f<T1, T2, ...>?
};

例如,如果 f在类外声明为 template<class...Ts>f(A<Ts...>);那么是的,它们是等价的。

关于c++ - 友元函数声明中的尖括号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52749794/

相关文章:

c++ - OpenGL 灰度纹理作为浮点格式错误

c++ - 我不断收到错误 "no match for call ' (std::vector<int>) (int)”

c++ - 解决 GCC 5.5 unordered_map 错误

C++:强制模板类型实现一个方法

c++ - 定义类模板构造函数的两种方式之间的区别

C++初学者,执行窗口消失得很快

c++ - 如何减少基于 MingW 的 GUI 应用程序的内存消耗?

templates - 动态 Mandrill 模板是否支持对集合进行迭代?

c++ - 将 std::bind 创建的对象传递给函数的正确方法是什么?

c++ - 将矩阵 `(*sp)[i]` 的行 `shared_ptr<vector<vector<T>> sp` 传递给接受 `shared_ptr<vector<T>>` 的函数