Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template deduction with Eigen arguments

template <typename Derived>
void Fun(const std::vector<Eigen::MatrixBase<Derived>> &seqs);

void Test() {
  std::vector<Eigen::MatrixXd> _seqs;
  Fun(_seqs);
}

As tutored by functions taking eigen types, Eigen::MatrixBase<Derived> should accept Eigen::MatrixXd. However, the above code could not compiled with error message says mismatched types ‘Eigen::MatrixBase<Derived>’ and ‘Eigen::Matrix<double, -1, -1>’ and the template arguments deduction failed.

So why this happens and how should we deal with it?

Thanks

like image 616
jkjkjk Avatar asked Apr 19 '26 13:04

jkjkjk


1 Answers

This is because the rule that template-name<T> as a whole parameter (ignoring reference and cv-qualifiers) can be deduced from D if D is derived from template-name<T> for some T. This rule does not apply for std::vector<template-name<T>>.

Even if you explicitly specify the type, since there is no valid conversion from std::vector<Derived> to std::vector<Base>, the call is still ill-formed.

Besides S.M.'s solution, you can use meta programming.

template <
    typename T,
    // enable only if T is derived from Eigen::MatrixBase<T>
    typename std::enable_if_t<std::is_base_of<Eigen::MatrixBase<T>, T>::value, int> = 0
>
void Fun(const std::vector<T>&);
like image 83
xskxzr Avatar answered Apr 21 '26 01:04

xskxzr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!