templated friend function lookup

前端 未结 1 582
你的背包
你的背包 2021-01-19 21:49

The following simple code compiles fine

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)          


        
相关标签:
1条回答
  • 2021-01-19 22:13

    The fix is to separate declaration and definition:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题