模板化的朋友函数查找

时间:2013-04-01 14:55:49

标签: c++ templates c++11 clang friend

以下简单代码编译正确

class A {
  int x[3];
public:
  A() { x[0]=1; x[1]=2; x[2]=3; }
  friend int const&at(A const&a, unsigned i) noexcept
  {
    return a.x[i];
  }
  friend int foo(A const&a, unsigned i) noexcept
  {
    int tmp = at(a,i);
    return tmp*tmp;
  }
};

但如果朋友是模板

class A {
  int x[3];
public:
  A() { x[0]=1; x[1]=2; x[2]=3; }

  template<unsigned I>
  friend int const&at(A const&a) noexcept
  {
    static_assert(I<3,"array boundary exceeded");
    return a.x[I];
  }

  template<unsigned I>
  friend int foo(A const&a) noexcept
  {
    int tmp = at<I>(a);   // <- error: use of undeclared identifier 'at'
    return tmp*tmp;
  }
};

查找规则发生变化,clang抱怨说错误,但gcc和icpc没有。谁是对的(C ++ 11)?以及如何为clang修复代码?

1 个答案:

答案 0 :(得分:4)

修复是分离声明和定义:

class A {
  int x[3];
public:
  A() { x[0]=1; x[1]=2; x[2]=3; }

  template<unsigned I>
  friend int const&at(A const&a) noexcept;

  template<unsigned I>
  friend int foo(A const&a) noexcept;
};

template<unsigned I>
int const&at(A const&a) noexcept
{
  static_assert(I<3,"array boundary exceeded");
  return a.x[I];
}

template<unsigned I>
int foo(A const&a) noexcept
{
  int tmp = at<I>(a);
  return tmp*tmp;
}