Eclipse C ++上的矢量实例化的模板参数无效

时间:2015-12-03 14:34:28

标签: c++ eclipse vector

我在c ++中有这样的代码:

#include <iostream>
#include <vector>

using namespace std;

.....................
.....................

int main(void)
{
    std::vector<std::shared_ptr<Object>> objects, fitting_objects;

    objects.push_back(new Rectangle(10, 10, 20, 20)); // classic polymorphism spectacle

    // rectangle for the area containing the objects we're looking for
    Rectangle r(5, 5, 30, 30);

    for(auto const& object : objects)
        if(object.fitsIn(r))
            fitting_objects.push_back(object);

    return 0;
}

我不明白为什么我会收到“无效的模板参数”错误。有类似的人和我一起经历过同样的问题。我已经实施了他们所拥有的相同解决方案,但我无法继续下去。

我该如何解决问题?

1 个答案:

答案 0 :(得分:2)

std::shared_ptr constructor is explicit。您需要push_back shared_ptr或使用std::vector::emplace_back而不是

objects.push_back(std::make_shared<Rectangle>());
objects.emplace_back(new Rectangle(10, 10, 20, 20)); // OK, careful if emplace_back throws, thanks @Simple

重现问题的最小示例:

#include <iostream>
#include <memory>
#include <vector>

struct X{};

int main()
{
    std::vector<std::shared_ptr<X>> v;
    // v.push_back(new X); // does not compile
    v.push_back(std::shared_ptr<X>(new X)); // OK
    v.emplace_back(new X); // OK, careful if emplace_back throws, thanks @Simple
}