在类Density
的声明中,我构建了这些成员函数:
class Density {
public:
template <typename Container>
void printStream (Container<Point>::iterator lo, Container<Point>::iterator hi);
......
};
在cpp文件中:
template <typename Container>
void Density::printStream (Container<Point>::iterator lo, Container<Point>::iterator hi)
{
...
}
但是在尝试编译时会遇到这些错误:
src/../include/density.hpp:166:23: error: 'Container' is not a template
src/../include/density.hpp:166:50: error: expected unqualified-id before 'lo'
src/../include/density.hpp:166:50: error: expected ')' before 'lo'
src/../include/density.hpp:166:50: error: expected initializer before 'lo'
src/density.cpp: In member function 'void Density::startAlgorithm()':
src/density.cpp:291:43: error: 'printStream' was not declared in this scope
src/density.cpp: At global scope:
src/density.cpp:327:28: error: 'Container' is not a template
src/density.cpp:327:55: error: expected unqualified-id before 'lo'
src/density.cpp:327:55: error: expected ')' before 'lo'
src/density.cpp:327:55: error: expected initializer before 'lo'
我应该修改什么?而且,为什么,因为我想了解这个问题。
答案 0 :(得分:4)
NB。如评论所述,您可能不了解使用模板对头文件中模板定义的可见性的影响。让我指出c++-faq的Why can templates only be implemented in the header file?条目:{{3}}
使用模板模板参数:
template <template <typename...> class Container>
void Density::printStream ()
{
typename Container<Point>::iterator lo;
typename Container<Point>::iterator hi;
}
你想要做什么,在我看来是不可能的,因为迭代器参数是不可推导的上下文,所以你最终会明确地指定容器类型:
density_instance.printStream<std::vector>(it1, it2);
但请注意,这并不是一个真正的问题,因为您可能并不真正关心容器的精确类型。惯用的方式是:
template <typename It>
void printStream (It lo, It hi);
您可以使用
自由拨打电话std::vector<int> v { 1,2,3 };
density_instance.printStream(begin(v), end(v));
但是对于非类容器,因为迭代器是重要的:
const int a[] = { 1,2,3 };
density_instance.printStream(std::begin(a), std::end(b));