gpt4 book ai didi

c++ - boost::multi_array 示例的 pretty-print 失败

转载 作者:行者123 更新时间:2023-11-28 08:11:10 24 4
gpt4 key购买 nike

我有这个聪明又酷的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 文件中,错误再次出现!

最佳答案

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

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

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

您的问题应该会消失。

关于c++ - boost::multi_array 示例的 pretty-print 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9034554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com