简体   繁体   中英

Friend function defined inside class template. Function template redefinition error

Below are two code samples. The first one defines operator+() for a class template Vector while the second one just declares the function but moves the function definition outside the class body. The first sample results in the following error:

main.cpp(4): error C2995:
'Vector<L,T> operator +(const Vector<L,T> &,const Vector<L,T> &)' :
function template has already been defined

Here are my questions:

  1. Why do the two template instantiations in main() result in function template redefinition errors? Based on my understanding, they should result in unique instances as the template parameters are different.
  2. How does moving the function definition outside of the class body resolve the error?

Error sample:

template<int L, typename T>
class Vector {

  template<int L, typename T> friend
  Vector<L, T> operator+(const Vector<L, T>& lhs, const Vector<L, T>& rhs) {
    return Vector<L, T>();
  }

private:
  T data[L];
};

int main() {
  Vector<42, double> v42d;
  Vector<24, int> v24i;

  return 0;
}

Working sample:

template<int L, typename T>
class Vector {

  template<int L, typename T> friend
  Vector<L, T> operator+(const Vector<L, T>& lhs, const Vector<L, T>& rhs);

private:
  T data[L];
};

template<int L, typename T>
Vector<L, T> operator+(const Vector<L, T>& lhs, const Vector<L, T>& rhs) {
  return Vector<L, T>();
}

int main() {
  Vector<42, double> v42d;
  Vector<24, int> v24i;

  return 0;
}

The template types L and T are already known, so don't need to be reintroduced. In fact doing so for the friend function causes them to overshadow the ones defined for the class.

this fixes it:

template<int L, typename T>
class Vector {

    friend
    Vector<L, T> operator+(const Vector<L, T>& lhs, const Vector<L, T>& rhs) {
        return Vector<L, T>();
    }

private:
    T data[L];
};

which is equivalent to:

template<int L, typename T>
class Vector {

    friend
    Vector operator+(const Vector& lhs, const Vector& rhs) {
        return Vector();
    }

private:
    T data[L];
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM