2012-01-27 69 views
0

我有这样的聪明和冷静example的boost :: multi_array的例子相当打印失败

#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目录/升压/ 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 

什么错了?它似乎不了解第一个和第二个功能之间的差别打印功能。也许我错过了一些编译器选项?

编辑: 如果我使用模板<>作为Craig H答案我解决了孤立example.cpp中的问题。但是,如果我将2个函数放在我的项目中的单独.h文件中,则错误再次出现!

回答

1

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

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

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

您的问题就会消失。

+0

你是对的!那么,这是什么? boost示例中的错误?怎么说,以提高家伙? – nkint 2012-01-27 14:33:25

+0

当你第一次发布这篇文章时,我没有看到链接,但是在增强示例中看起来像一个错误。模板专门化是告诉编译器该函数是特定类型的特定版本模板函数的方式。如果你对这个网站感兴趣:http://www.cplusplus.com/doc/tutorial/templates/对模板和专业化有很好的描述。 – 2012-01-27 14:39:17

+0

感谢您的链接!但我有另一个问题。如果我在我的应用程序中包含这2个函数,我得到这个错误:**多重定义void void print_multi_array (std :: basic_ostream >&,double const&)'** – nkint 2012-01-27 15:27:30