简体   繁体   中英

Eclipse polymorphism using C++11 shared_ptr error

Given the following sample code:

#include <iostream>
#include <memory>
using namespace std;

struct A {
public:
    A(int aa) : a(aa) {}
    int a;
    virtual ~A() {}
};
struct B : A {
public:
    B(int aa, int bb) : A(aa), b(bb) {}
    int b;
};

void f(shared_ptr<A> a){
    shared_ptr<B> b = dynamic_pointer_cast<B>(a);
    if (b) {
        cout << b->b << endl;
    } else {
        cout << a->a << endl;
    }
}

int main() {
    auto a = make_shared<A>(3);
    auto b = make_shared<B>(7, 4);
    f(a);
    f(b);
    return 0;
}

Eclipse indicates that there is an error on the line

f(b);

saying Invalid arguments ' Candidates are: void f(std::shared_ptr<A>) '
because a shared_ptr<B> has been passed. This compiles and runs, and has output:

3
4

as expected.

The indexer and compiler have -std=c++11 specified.
The compiler also has the symbol __GXX_EXPERIMENTAL_CXX0X__ defined.

Is there any way to get rid of this error and its red squiggles in Eclipse (preferably without modifying the source)?

我建议您在可能不支持C ++ 11的设置中禁用静态代码分析插件Codan。

This has been fixed in later versions of CDT (I just tried it).

You can use a nightly build of CDT using this repository: Go to Help, and enter the url http://download.eclipse.org/tools/cdt/builds/kepler/nightly

If you don't feel like using a nighty build, you should at least make sure you have the latest released version (at this writing it is 8.1.1), using http://download.eclipse.org/tools/cdt/releases/juno/

My full setup of eclipse with C++11 is found here: http://scrupulousabstractions.tumblr.com/post/36441490955/eclipse-mingw-builds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM