我在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;
}
我不明白为什么我会收到“无效的模板参数”错误。有类似的人遇到过与我相同的问题。我已经实现了与他们相同的解决方案,但我无法更进一步。
我该如何解决这个问题?
最佳答案
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
}
关于c++ - Eclipse C++ 上 vector 实例化的无效模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34068681/