C ++参数类型,用于接受适用于基于范围的for循环的所有序列

时间:2018-04-05 15:17:08

标签: c++ stl containers

例如,我有一个使用C ++ 11 range-based for loop语法的函数:

void myFunc(const std::vector<char>& bytes) {
    for (char b : bytes) {
        // do something useful to every byte
    }
}

如何更改此函数声明以接受每个合适的序列容器,即不仅std::vector<char>,还std::array<char>std::string等?

根据我所学到的,基于范围的for循环依赖于给定begin()的{​​{1}}和end()方法的存在。通常,在其他语言中,这意味着所有可迭代容器共享某种通用接口,可用于为此类参数传递任意容器,但看起来C ++没有像这样的容器层次结构。相反,C ++似乎有&#34;概念&#34;,如Container,但它只能在编译器内部访问,我认为?

2 个答案:

答案 0 :(得分:6)

我认为这可以解决问题

template<typename T>
void myFunc(const T& bytes) {
    for (auto b : bytes) {
        // do something useful to every byte
    }
}

答案 1 :(得分:2)

使用概念,您可以转换@ rak007的

template<typename T>
void myFunc(const T& bytes) {
    for (auto b : bytes) {
        // do something useful to every byte
    }
}

进入(无限小)更明确的

template<Container T>
void myFunc(const T& bytes) {
    for (auto b : bytes) {
        // do something useful to every byte
    }
}

C ++的容器已经符合(系列)公共接口,但该接口是编译时构造。 Concepts提供的是指定这些接口的语言工具,而不是文档内(或规范中)工具。