yusuf
yusuf

Reputation: 3781

Invalid Template Argument for vector instantiation on Eclipse C++

I have such a code in 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;
}

I don't understand why I get "invalid template argument" error. There are similar people who has experienced the same problem with me. I have implemented the same solution they had, but I couldn't go further.

How can I fix the problem?

Upvotes: 0

Views: 897

Answers (1)

vsoftco
vsoftco

Reputation: 56567

std::shared_ptr constructor is explicit. You need to push_back a shared_ptr or use std::vector::emplace_back instead

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

Minimal example that reproduces the issue:

#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
}

Upvotes: 2

Related Questions