编译期间未找到模板化函数
templated function not found during compilation
我有一个矩阵类,它支持使用运算符重载实现的标量值的操作。由于除了使用的运算符之外,每个重载运算符函数都具有相同的主体,因此我决定创建一个泛型函数,该函数将接受一个函数以及矩阵和标量值来合并我的代码。
下面是泛型函数,它从重载的加法运算符函数调用:
// 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
,不能满足朋友矩阵的声明。为什么?让我们尝试对可以使用float
和std::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);
- 跨模板化函数编译的静态变量
- 无法使用 LoadObject() 函数编译 UE4 Actor。
- 为什么在使用转换构造函数编译代码时需要 const 复制构造函数?
- 函数编译,即使它不接受整数
- 使用C 模板函数编译时间递归
- 安卓 JNI - 'raw'函数编译失败
- C++就地析构函数编译警告
- 对 TR1 使用 boost 时提升数学特殊函数编译错误
- 显式复制构造函数编译错误
- 使用SSE内部函数编译一个简单的c++程序
- 函数编译时错误
- 模板函数编译错误
- C++:使用类型名作为基的模板类调用函数编译时错误
- 将 MATLAB 函数编译成可以在 linux 终端上运行的东西,w.out MATLAB
- boost::绑定不要使用成员模板函数编译
- C++函数编译错误
- 加速模板函数编译
- 如何在C++中使用辅助函数编译以下flex文件
- 如何让g++使用move构造函数编译c++11代码
- 同时将一组函数编译为.LIB和.DLL