【问题标题】:pretty print of boost::multi_array example failsboost::multi_array 示例的漂亮打印失败
【发布时间】:2012-01-27 14:15:24
【问题描述】:

我有这个聪明又酷的example

#include <iostream>
#include "boost/multi_array.hpp"
#include "boost/array.hpp"
#include "boost/cstdlib.hpp"

template <typename Array>
void print(std::ostream& os, const Array& A)
{
  typename Array::const_iterator i;
  os << "[";
  for (i = A.begin(); i != A.end(); ++i) {
    print(os, *i);
    if (boost::next(i) != A.end())
      os << ',';
  }
  os << "]";
}
void print(std::ostream& os, const double& x)
{
  os << x;
}
int main()
{
  typedef   boost::multi_array<double, 2> array;
  double values[] = {
    0, 1, 2,
    3, 4, 5 
  };
  const int values_size=6;
  array A(boost::extents[2][3]);
  A.assign(values,values+values_size);
  print(std::cout, A);
  return boost::exit_success;
}

但是如果我尝试编译它:g++ -I/usr/include/boost/b.cpp我得到这个错误:

b.cpp: In function ‘void print(std::ostream&, const Array&) [with Array = double]’:
b.cpp:12:   instantiated from ‘void print(std::ostream&, const Array&) [with Array = boost::detail::multi_array::const_sub_array<double, 1u, const double*>]’
b.cpp:12:   instantiated from ‘void print(std::ostream&, const Array&) [with Array = main()::array]’
b.cpp:32:   instantiated from here
b.cpp:9: error: ‘double’ is not a class, struct, or union type
b.cpp:11: error: request for member ‘begin’ in ‘A’, which is of non-class type ‘const double’
b.cpp:9: error: ‘double’ is not a class, struct, or union type
b.cpp:9: error: request for member ‘end’ in ‘A’, which is of non-class type ‘const double’
b.cpp:9: error: ‘double’ is not a class, struct, or union type
b.cpp:9: error: ‘double’ is not a class, struct, or union type
b.cpp:9: error: ‘double’ is not a class, struct, or union type
b.cpp:13: error: request for member ‘end’ in ‘A’, which is of non-class type ‘const double’
b.cpp:9: error: ‘double’ is not a class, struct, or union type

shell returned 1

出了什么问题?似乎不明白第一个和第二个 print 函数的区别。也许我错过了一些编译器选项?

编辑: 如果我使用 template 作为 Craig H 的答案,我会在一个孤立的 example.cpp 中解决问题。但是如果我把这2个函数放在我项目中的一个单独的.h文件中,错误又会出现!

【问题讨论】:

    标签: c++ boost multidimensional-array


    【解决方案1】:

    在此示例中,您创建了一个模板函数作为您的第一个打印函数,然后声明了另一个函数,该函数实现了该模板的特定版本而无需模板专门化。我想如果你改变以下行

    void print(std::ostream& os, const double& x)
    

    template<> void print<double>(std::ostream& os, const double& x)
    

    您的问题应该会消失。

    【讨论】:

    • 你是对的!那么,这是什么?提升示例中的错误?怎么说才能提振男生?
    • 当您第一次发布此链接时,我没有看到链接,但这在 boost 示例中看起来确实是一个错误。模板特化是告诉编译器该函数是特定类型的模板函数的特定版本的方式。如果您对此站点感兴趣:cplusplus.com/doc/tutorial/templates 对模板和专业化有很好的描述。
    • 感谢您的链接!但我还有另一个问题。如果我在我的应用程序中的 .h 中包含这 2 个函数,我会收到此错误:multiple definition of `void print_multi_array(std::basic_ostream >&, double const&) '
    • 带有静态关键字的也无法编译.. : (
    猜你喜欢
    • 2023-03-07
    • 2013-11-08
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多