1

在类的声明中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'

我应该修改什么?还有,为什么,因为我想了解这个问题。

4

1 回答 1

4

注意。正如所评论的,您可能没有意识到使用模板对头文件中模板定义的可见性的影响。让我为您指出条目:为什么模板只能在头文件中实现?


使用模板模板参数

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));
于 2013-06-09T17:08:52.823 回答