模板类的模板朋友功能 [英] Template friend function of template class

查看:50
本文介绍了模板类的模板朋友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果函数的模板参数包括但不限于类的模板参数,如何使函数成为类的朋友并在类外部定义函数.

I am wondering how to make a function friend of a class and define the function outside class if the function's template arguments include but are not limited to the class's template arguments.

例如,我具有以下模板类和模板朋友功能:

For example, I have the following template class and template friend function:

template<int N>  class Matrix;
template<typename T, int N> Matrix<N> operator*(const Matrix<N> &m1, const T &m2);

// class definition
template<int N>
class Matrix{
  template<typename T>
  friend Matrix<N> operator* (const Matrix<N> &m1, const T &m2);
};

// friend function definition
template<typename T, int N> Matrix<N> operator*(const Matrix<N> &m1, const T &m2)
{
    return m1; // just as an example
}

如果我编译:

Matrix<3> m;
m * 1.0;

我会收到以下链接器错误:

I would get the following linker error:

test.cc:(.text+0x1c7): undefined reference to `Matrix<3> operator*<double>(Matrix<3> const&, double const&)'
collect2: error: ld returned 1 exit status

推荐答案

您的实物不匹配.

您的初始声明和以后的定义均具有以下签名:

Your initial declaration, and later definition, have this signature:

template<typename T, int N>
Matrix<N> operator*(const Matrix<N> &m1, const T &m2);

这是一个具有两个模板参数的功能模板: T N .

This is a function template taking two template parameters: T and N.

但是,在您的班级中,您将具有以下签名的功能模板作为朋友进行了制作:

However, within your class, you make as a friend a function template that has this signature:

template<typename T>
friend Matrix<N> operator* (const Matrix<N> &m1, const T &m2);

这只有一个一个模板参数: T . N 已在此处修复.这个朋友声明也声明了这个函数模板.这是一个更好的匹配,但实际上没有定义,因此可以看到您的行为.

This only has one template parameter: T. N is fixed here. This friend declaration also declares this function template. This is a better match, but not actually defined, hence the behavior you see.

我认为您有两种选择.

  1. 删除 operator * 的名称空间范围声明,然后在 Matrix 的定义内声明并定义友好的 operator * .

  1. Remove the namespace-scope declaration of operator* and just declare and define the friended operator* within the definition of Matrix.

更改好友声明以匹配命名空间范围声明:

Change the friend declaration to match the namespace-scope declaration:

template<typename T, int M>
friend Matrix<M> operator* (const Matrix<M> &m1, const T &m2);

(1)通常是更好的选择-不需要在全局范围内添加更多的 operator * ,这对于编译时很有用.

(1) is the better option typically - doesn't involve adding more operator*s into global scope, which is good for compile times.

这篇关于模板类的模板朋友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆