C++ 模板类的模板友元函数

C++ 模板类的模板友元函数,c++,visual-c++,templates,friend-function,C++,Visual C++,Templates,Friend Function,我一直在努力解决(将模板函数声明为模板类的朋友)中描述的问题,我相信第二个答案就是我想要做的(向前声明模板函数,然后将专门化命名为朋友)。我有一个问题,即一个稍微不同的解决方案是否正确,或者恰好在Visual C++ 2008中工作。 测试代码为: #include <iostream> // forward declarations template <typename T> class test; template <typename T> std::

我一直在努力解决(将模板函数声明为模板类的朋友)中描述的问题,我相信第二个答案就是我想要做的(向前声明模板函数,然后将专门化命名为朋友)。我有一个问题,即一个稍微不同的解决方案是否正确,或者恰好在Visual C++ 2008中工作。 测试代码为:

#include <iostream>

// forward declarations
template <typename T>
class test;

template <typename T>
std::ostream& operator<<(std::ostream &out, const test<T> &t);

template <typename T>
class test {
  friend std::ostream& operator<< <T>(std::ostream &out, const test<T> &t);
  // alternative friend declaration
  // template <typename U>
  // friend std::ostream& operator<<(std::ostream &out, const test<T> &t);

  // rest of class
  };

template <typename T>
std::ostream& operator<<(std::ostream &out, const test<T> &t) {
  // output function defined here
  }
#包括
//转发声明
模板
课堂测试;
模板

std::ostream&operator…如果我意外地更改了operator的转发声明,我发现使用名称空间std添加
将消除对转发声明的需要,我猜这是(可能的)编译器错误的副作用。根据我的评论,你能显式地添加你说有效的示例(包括实例化)吗?口头上很难理解你对每个例子的意思。最初我认为它像你描述的那样工作,但它没有(这就是我问这个问题的原因)。当我说“一切都能正确编译和工作”时,我实际上是指我能够成功地实例化类并使用
,而且我意识到你可能误解了我所说的“假”声明——我只是说在类之前更改转发声明;类中的一个仍然与我稍后实现的函数相匹配(因此在实例化时,所需的函数模板已经被解析)。@Sumudu:我添加了一个更新的,以解决您的第二个注释。对于第一个问题,您是否可以修改您的问题,使其包含您所说的“编译并正确工作”但使用备选friend函数模板的示例?当我在这里这样做时,我会在访问命名空间模板中的成员时出错。
template class test<int>;
friend std::ostream& operator<<  <
class A {};
template <typename T> A & operator<<(A &, int);

void foo () {
  A a;
  operator<< <int> (a, 10);
}
template <typename T>
class test {
  template <typename U> 
  friend std::ostream& operator<<(std::ostream &out, const test<T> &t);
  };

template <typename T> 
std::ostream& operator<<(std::ostream &out, const test<T> &t);  // NOT FRIEND!
template <typename U> 
std::ostream& operator<<(std::ostream &out, const test<int> &t);
template <typename U> 
std::ostream& operator<<(std::ostream &out, const test<char> &t);
template <typename U>
std::ostream& operator<<(std::ostream &out, const test<float> &t);
int main ()
{
  test<int> t;
  operator<< <int> (std << cout, t);
  operator<< <float> (std << cout, t);
  operator<< <char> (std << cout, t);
}
friend std::ostream& operator<<  <