我有这个聪明而又酷的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
出了什么问题?它似乎无法理解第一个和第二个打印功能之间的区别。也许我错过了一些编译器选项?
编辑: 如果我使用模板&lt;&gt;正如克雷格H回答我在一个孤立的example.cpp中解决问题。但是,如果我将2个函数放在项目中的单独.h文件中,则会再次出现错误!
答案 0 :(得分:1)
在此示例中,您创建了一个模板函数作为第一个打印函数,然后声明另一个函数,该函数实现该模板的特定版本而不使用模板专业化。我想如果你改变以下行
void print(std::ostream& os, const double& x)
到
template<> void print<double>(std::ostream& os, const double& x)
你的问题应该消失。