【问题标题】:Templated functions for boost matrices in C++C++中boost矩阵的模板化函数
【发布时间】:2017-08-21 04:31:09
【问题描述】:

我需要一个函数以我希望看到的格式打印出向量的元素。目前我对vector<double>vector<std::complex>有单独的函数,如下:

void printvd(boost::ublas::vector<double> V) {
    for( int i=0;i<V.size();i++ )
      std::cout << V(i) << " ";
}
void printvc(boost::ublas::vector<std::complex> V) {
    for( int i=0;i<V.size();i++ )
      std::cout << V(i) << " ";
}

我试过用模板,

template<typename T>
void printv(boost::ublas::vector<T > V) {
    for( int i=0;i<V.size();i++ )
      std::cout << V(i) << " ";
}

但任何调用(如printv&lt;double&gt;(V);)总是以未定义的引用错误结束。

我也面临与矩阵类似的问题 - 任何帮助将不胜感激。如果有人能打趣一下如何在 boost 中使用矩阵表达式,那也很好。

【问题讨论】:

  • 未定义的引用意味着你应该在编译时链接来提升。还要确保将模板函数放在头文件中,而不是放在 cpp 源文件中。这是问题的另一个可能原因。
  • 好吧,我正在开发一个包含 5 个 cpp 文件(和相应的头文件)并使用 CMake 进行构建的项目。所以我认为问题不在于链接器。
  • 当你提出问题时,学会倾听。阅读我评论的第二部分。
  • 什么的未定义引用?你知道templates should be defined in the header files
  • [OT]:您可能应该通过 const 引用而不是值来获取参数。

标签: c++ templates matrix boost


【解决方案1】:

请确保您可以编译这个非常基本的示例,其中应解析所有路径和包含。

#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
#include <complex>

using std::cout;
using std::endl;

void printvd(boost::numeric::ublas::vector<double> V) {
    for( int i=0;i<V.size();i++ )
      std::cout << V(i) << " ";
}
void printvc(boost::numeric::ublas::vector<std::complex<double>> V) {
    for( int i=0;i<V.size();i++ )
      std::cout << V(i) << " ";
}

template<typename T>
void printv(boost::numeric::ublas::vector<T > V) {
  for( int i=0;i<V.size();i++ )
      std::cout << V(i) << " ";
}

int main(int argc, char *argv[])
{
  boost::numeric::ublas::vector<double> testVector1;
  boost::numeric::ublas::vector<std::complex<double>> testVector2;

  printv(testVector1);
  printv(testVector2);
  return 0;
}

以及对应的CMakeLists.txt:

project(boost_vector_test)
cmake_minimum_required(VERSION 2.8)
add_executable(${PROJECT_NAME} main.cpp)

否则 boost 有很好的文档,其中包含如何使用矩阵表达式的示例:http://www.boost.org/doc/libs/1_63_0/libs/numeric/ublas/doc/matrix_expression.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多