对模板化函数中的通用特征矩阵使用 Ref<>
Using Ref<> for generic Eigen matrices in a templated function
这里有一个我想写的函数:
template<typename NumType> using Vec = Eigen::Matrix<NumType, Eigen::Dynamic, 1>;
template<typename T>
void foo(Eigen::Ref<Vec<T>> p)
{
// fill p with things
}
void main()
{
Vec<double> v(2);
foo(v)
}
特别是,我希望能够在不向模板传递类型参数的情况下调用foo
,而是让函数通过参数推断类型。当我运行此代码时,我得到的错误
No matching function call to 'foo'
Candidate template ignored: could not match 'Ref' against 'Matrix'
如果我将类型传递给函数调用,例如foo<double>(v)
,则此函数可以正常工作。我还知道如果foo
的签名是,则可以推断出类型T
template<typename T>
void foo(Vec<T> & p)
但这不是通过引用传递特征向量的好方法,因为它破坏了表达模板的好处。
我也不能使用通过参考的MatrixBase
方法
template<typename Derived>
void foo(Eigen::MatrixBase<Derived>& p)
因为我想确保传入的向量是T
类型的,而我不知道如何用这个方法来确保这一点。
有没有一种方法可以在像这样的模板函数中使用Ref<>
来推断类型T
?感谢所有的帮助。
对于模板代码,请使用MatrixBase
方法,并且要控制标量类型,请使用静态断言或enable_if
构造。使用typename Derived::Scalar
获取表达式的标量类型。
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 将Ref对象作为类成员
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 为什么我的 std::ref 无法按预期工作?
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 如何将 Eigen::Ref 与 pybind11 一起使用?
- 如何@ref同一方法的不同变体?
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- std::bind 是否实现了 std::ref 和 std::cref 来消除函数调用的歧义?
- 为什么要用 ref-qualifier 和
- 将 ArrayXd 传递给 const VectorXd& 和 const Ref<const VectorXd>&
- 返回 Eigen::Ref 合法吗?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- 为什么添加析构函数(甚至是空的)会破坏我的结构,该结构使用 ref 转发和折叠来保存 ref 或值的副本?
- 在与Odint组合的类中使用特征矩阵Ref
- const-ref传递的模板化参数是否经过优化,以便在足够小时按值传递
- 带有自定义deleter的std::unique_ptr对象的大小(一个由ref捕获的lambda)