为什么没有尖括号的非限定模板函数的实例不能成为类的朋友?

时间:2011-12-30 20:45:50

标签: c++ templates

这是我的代码:

#include<iostream>

class foo;
template<typename T> void bar(T a) { std::cout<< a.var; }

class foo { 
    int var;
    public: 
      friend void bar(foo); //here, bar function template is declared in global namescope,
      // deduction can deduce which template instance we're talking about. 
      //Note: If I place <> just after name bar or qualify bar like ::bar , it all works then.
};

int main() {
    foo fooo;
    bar(fooo);
}

错误:/home/O1wLF2/cc1xOI20.o:在函数'main'中:prog.cpp :(。text + 0x46):未定义引用'bar(foo)'

我想知道为什么非合格模板函数的实例不能成为朋友?

1 个答案:

答案 0 :(得分:3)

您正在将非模板功能作为朋友。您需要告诉编译器您要将模板设为朋友或其中一个实例。