c++ - Templates::Stroustrup 的示例未编译

标签 c++ templates stl

“没有匹配的成员函数push_back”

在 Bjarne 的原始版本中,C 的 vector 是这样写的

vector<Value_type<C>*> res;

但是这个 Value_type 模板不能正常工作 所以我只是用 C* 指针替换它,仍然没有帮助

#include <vector>
#include <string>
#include <iostream>

using namespace std;

template <typename C, typename V>
vector<C*> find_all(C& c, V v) {
    vector<C*> res;
    for (auto &x : c) {
        if (x==v)
            res.push_back(&x);
    }
    return res;
}

int main() {
    string s = "werqewreqwreqw";
    for (const auto p : find_all(s,'q')) {
        cout << p;
    }

}

最佳答案

C*C::value_type* 不同.实际上,已经有一个表示相同概念的typedef,即C::pointer。 .

template <typename C, typename V>
vector<typename C::pointer> find_all(C& c, V v) {
    vector<typename C::pointer> res;

仅供引用,C::pointer将是 std::allocator_traits<T>::pointer ,这也是 T*对于默认分配器或 value_type* .我不完全确定为什么 Value_type被使用了,但我假设这是 Bjarne 的想法,用于替换 typename C::value_type 的元函数.

关于c++ - Templates::Stroustrup 的示例未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32730100/

相关文章:

c++ - 在 ipv6 链接范围单播 udp 客户端-服务器守护进程中应用 boost::asio::ip::udp,有时有效,但有时无效

c++ - 初始化依赖于私有(private)模板类型的静态类成员 (C++)

c++ - 类模板中的 Typedef 评估

c++ - std::initializer_list 的实现

c++ - 内部分布式时间服务器实现

c++ - 我应该在 C++11 中显式声明转换运算符吗?

c++ - 演示static_cast的目的和用途呢?

c++ - 从模板类的实例继承

C++ 如何将数组 int[10] push_back 到 std::vector<int[10]>?

c++ - STL vector 错误 : Unknown type name