c++ - 带有 Armadillo 的 C++ 函数模板

标签 c++ function templates armadillo

我正在使用 Armadillo 线性代数库编写一些函数模板,但遇到了一些错误。我仍在学习 C++ 及其方面,因此非常感谢任何可能的解决方案。我的大部分功能如下所示,

template<typename T1>
void some_function(const Mat<T1> & p)
{
    unsigned int n = p.n_rows;
    // do some stuffs...
    // ....
}

我的主要功能包括:

Mat<double> A = ones<Mat<double>>(4,4);
int a(2);
some_function(A);  // runs perfectly
some_function(a*A); // compilation error as follows

test_function.hpp:35:8: note: template argument deduction/substitution failed:
test.cpp:22:17: note: ‘arma::enable_if2<true, const arma::eOp<arma::Mat<double>, arma::eop_scalar_times> >::result {aka const arma::eOp<arma::Mat<double>, arma::eop_scalar_times>}’ is not derived from ‘const arma::Mat<eT>’
some_function(a*A);

如果我按如下方式更改函数:

template<typename T1>
void some_function(const T1 & p)
{
    unsigned int n = p.n_rows;
    // do some stuffs...
    // ....
}

然后给出编译错误如下:

test_function.hpp: In instantiation of ‘bool some_function(const T1&) [with T1 = arma::eOp<arma::Mat<double>, arma::eop_scalar_times>]’:
test.cpp:22:17:   required from here
test_function.hpp:37:26: error: ‘const class arma::eOp<arma::Mat<double>, arma::eop_scalar_times>’ has no member named ‘n_rows’
 unsigned int n = p.n_rows;

但是非模板函数工作得很好,比如

void some_function(const Mat<double> & p)
{
    unsigned int n = p.n_rows();
    // do some stuffs...
    // ....
}

有什么解决办法吗??

最佳答案

使用 .eval()强制将 Armadillo 表达式转换为矩阵的成员函数。

然后您可以使用 .eval() 的结果作为函数的输入。例如:

mat A(10,20,fill::randu);
mat B(10,20,fill::randu);

some_function( (A+B).eval() );

另请注意,Mat 类没有名为 n_rows() 的成员函数。相反,它有一个名为 n_rows 的只读变量.例如:

unsigned int n = X.n_rows;

关于c++ - 带有 Armadillo 的 C++ 函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32898620/

相关文章:

c++ - 如何在 0 个可变参数上专门化可变参数模板类?

C++模板类成员函数特化

c++ - 根据转换后的值查找最小元素

c++ - 常量和可变

function - 如何获取用于调用 powershell 函数的原始表达式?

javascript - 从 css 调用 <a> 标签到 javascript 函数

function - 在 Scala 中,为什么我们在定义方法时需要 "="?

c++ - 如何正确公开基础模板类型以用作类型

c++ - ODR-used 规则不适用于 visual studio

c# - 如何在 C# 中将 DLLImport 与结构作为参数一起使用?