C++ 为什么非限定模板函数是';不带尖括号的s实例可以';你不是班上的朋友吗?

C++ 为什么非限定模板函数是';不带尖括号的s实例可以';你不是班上的朋友吗?,c++,templates,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,

这是我的密码:

#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);
}
#包括
foo类;

模板void bar(ta){std::cout您正在使非模板函数成为朋友。您需要告诉编译器您希望使模板成为朋友或其中一个实例。

我不同意您的意见,请尝试运行相同的程序,包括仅限定
bar
而不使用()在MSVS中,它可以正常运行。类中的友元声明声明了一个名为bar()的非模板函数,并将一个foo对象作为参数。这与声明(和定义)的函数模板无关这是函数模板的重载,当参数类型完全匹配时,最好使用它它不可能是一个声明,而且显然找到了函数模板。不过有两件不同的事情。@Mr.Anubis:我不知道该代码到底应该证明什么或反驳什么,但这是您需要查看的代码。@DietmarKühl现在您的评论对我有意义了。谢谢:)