【发布时间】:2015-10-02 00:02:26
【问题描述】:
我正在使用犰狳线性代数库编写一些函数模板,但遇到了一些错误。我仍在学习 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...
// ....
}
有什么解决办法吗??
【问题讨论】:
-
似乎
operator *(double, Mat<double>)返回一个惰性评估,而不是直接返回一个Mat<double>... -
错误很明显。模板可以是
int。int有成员n_rows()吗? -
@manetsus 编号
int没有n_rows,但Mat<T1>有。在第二种情况下,由于我只传递Mat类(或int*Mat<>...),我认为只有该版本的函数将被实例化。 @Jarod42 是的,这可能是问题所在。 -
这意味着您想告诉您的第一个(问题中的五个)代码块出现错误,对吧?
-
@Jarod42 - 实际上该库确实提供了一种处理该问题的正确方法:.eval() 成员函数。例如:
my_function( (a*A).eval() )
标签: c++ function templates armadillo