c++ - STL 容器模板

标签 c++ templates stl

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'

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

最佳答案

注意。如评论所述,您可能没有意识到使用模板对头文件中模板定义的可见性的影响。让我给你指点条目:Why can templates only be implemented in the header file?


使用模板模板参数:

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));

关于c++ - STL 容器模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012066/

相关文章:

c++ - 如何在 C++ 中的 2 个函数集之间切换?

c++ - LLVM 有后端优化器吗?

templates - g:render标签将body()呈现为纯文本

javascript - 通过 ruby​​ 服务器执行 javascript 模板生成 HTML?

c++ - 如何将标准生成器传递给 STL 函数?

c++ - 放置到 std::map 的 std::map

c++ - 嵌套类和构造函数调用理解

c++ - 如何找到全局静态初始化

c++ - 具有模板化基类 : Base<Derived> 的菱形继承(钻石问题)

c++ - Visual C++ Express、调试器、排序关联容器和内存释放