eigen:模板函数中矩阵的默认类型

Eigen: Default type for MatrixBase in template function?

本文关键字:默认 类型 函数 eigen      更新时间:2023-10-16

假设我有一些功能可以选择模板类型的可选参数。

template<typename Scalar = int>
void foo(Scalar *out = NULL)
{
    std::cout << "HI!" << std::endl;
    if(out != NULL)
        *out = 42;
}
float x = 10;
foo(&x);//Call with optional argument
foo();//Call without optional argument

当然,如果没有可选参数,编译器就无法从呼叫中推导出可选的参数类型,但是我们可以通过指定默认模板参数来帮助它。

template<typename Scalar = int>

假设我现在有真实的示例eigen

template</*some template args*/, typename Derived>
void solve(/*some args*/, std::vector<Eigen::MatrixBase<Derived>> *variablePath)

我的问题是 - 如何为Derived指定一些默认类型?例如,我想将变量路径的默认类型为 std::vector<Eigen::MatrixXf> *

当然我可以使用一些常见的模板参数,而不是Eigen::MatrixBase<Derived>,例如

template</*some template args*/, typename Matrix = Eigen::MatrixXf>
void solve(/*some args*/, std::vector<Matrix> *variablePath)

,但我认为这很脏

ps对不起我的英语

我想您也想默认变量为nullptr,因此只需编写一个没有可选参数的超载:

template</*some template args*/, typename MatType>
void solve(/*some args*/, std::vector<MatType> *variablePath);
template</*some template args*/>
void solve(/*some args*/) {
  std::vector<MatrixXf> *nullvector = nullptr;
  solve(/*some args*/, nullvector);
}