编译期间未找到模板化函数

templated function not found during compilation

本文关键字:函数 编译      更新时间:2023-10-16

我有一个矩阵类,它支持使用运算符重载实现的标量值的操作。由于除了使用的运算符之外,每个重载运算符函数都具有相同的主体,因此我决定创建一个泛型函数,该函数将接受一个函数以及矩阵和标量值来合并我的代码。

下面是泛型函数,它从重载的加法运算符函数调用:

// Generic function to take care of matrix operations
template<typename T, typename F>
Matrix<T> scalar_operation(const Matrix<T> &a, const T b, F f) {
std::vector<std::vector<T> > new_els = a.elements;
typename std::vector<std::vector<T> >::iterator it = new_els.begin();
typename std::vector<T>::iterator it_in;
for (; it != new_els.end(); ++it) {
it_in = it->begin();
for (; it_in != it->end(); ++it_in) {
*it_in = f(*it_in, b);
}
}
return Matrix<T>(new_els);
}
// Add scalar to all values in Matrix
template<typename T>
Matrix<T> operator+(const Matrix<T> &a, const T b) {
return scalar_operation(a, b, std::plus<T>()); 
}

以下是在矩阵类中声明的函数:

template<class T>
class Matrix {
template<typename F>
friend Matrix<T> scalar_operation(const Matrix<T> &a, const T b, F f);
friend Matrix<T> operator+<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator-<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator*<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator/<>(const Matrix<T> &a, const T b);

当我单独实现重载运算符函数时,它们起作用了,但是通过此实现,我收到以下编译器错误:

Undefined symbols for architecture x86_64:
"Matrix<float> scalar_operation<std::__1::plus<float> >(Matrix<float> const&, float, std::__1::plus<float>)", referenced from:
Matrix<float> operator+<float>(Matrix<float> const&, float) in matrix_test-3188cd.o
ld: symbol(s) not found for architecture x86_64

我想我的错误与Matrix<float> scalar_operation<std::__1::plus<float> >(行有关,因为它看起来链接器正在搜索具有此标头的函数,这与它在我的文件中声明的方式略有不同,但我尝试修改我的声明,它抛出其他错误。

为什么我会收到此错误,如何解决?谢谢!

编辑:为了消除一些混淆,所有代码都在头文件中实现,因为它是一个模板化类。没有相应的.cpp文件。

代码有以下问题:类Matrix声明 friend 函数friend template<typename F> scalar_operation(...)(是的,friend 关键字不仅声明私有访问,它还声明函数),但在外部范围内没有这样的函数。只有template<typename T, typename F> scalar_operation,不能满足朋友矩阵的声明。为什么?让我们尝试对可以使用floatstd::plus<float>进行的伪编码实例化(为简短起见,省略了返回值和参数):
friend scalar_operation<std::plus<float>>(...)

scalar_operation<float, std::plus<float>>(...)
正如我们所看到的,它们是不同的。因此,在编译过程中我们没有问题:我们有适当的朋友scalar_operation声明,满足operator+内部的调用约定。但是无法对这种声明进行定义,并且在链接时遇到问题。解决方案是一个正确的朋友声明:
template<typename TT, typename F> friend Matrix<TT> scalar_operation(const Matrix<TT> &, const TT, F);