C++ 模板函数返回基于模板参数的类型

标签 c++ c++11 templates

我想创建一个函数来创建不同类型的生成器(自己的类),我会使用这样的方法:

template <typename Iterator>
class Generator {
Iterator begin_;
Iterator end_;
public:
Generator(Iterator begin, Iterator end)
    : begin_(begin)
    , end_(end)
    {}
};

template <typename GeneratorType, typename ContainerIterator>
GeneratorType<ContainerIterator> make_generator(ContainerIterator begin, ContainerIterator end){ // Error occurs here
    return GeneratorType<ContainerIterator>(std::forward<ContainerIterator>(begin), std::forward<ContainerIterator>(end));
}

但由于错误而无法编译:

error: 'GeneratorType' is not a template (in line GeneratorType<ContainerIterator> make_generator...)

有谁知道这是否可能,如果可以如何解决?

最佳答案

改变make_generator的定义

template <template<class> class GeneratorType, typename ContainerIterator>
GeneratorType<ContainerIterator> make_generator(ContainerIterator begin, ContainerIterator end)

您可以将模板作为参数传递给其他模板。但是参数定义需要指定为期望模板模板参数。

关于C++ 模板函数返回基于模板参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41461446/

相关文章:

c++ - 多线程时一直调用对象析构函数,但对象没有超出范围

c++ - constexpr 数组未定义

c++ - 随机数生成器最小和最大边界,不起作用?

c++ - 如何使用构造函数(带参数)创建模板类并将该类的方法传递给线程

templates - 未知类型名称 ‘vector’

c++ - 对象中 vector 中的 push_back

c++ - C++ 中的 open cv 中有维纳函数吗?

C++绘制矩形位置

c++ - 通过 cmake 文件在 Eclipse 中设置编译器特定设置和项目构建位置

c++ - 使用类模板需要模板参数列表?