How do i use 'auto' in C++ (C++0x)?

这一生的挚爱 提交于 2019-12-11 16:31:17

问题


What do i have to do to this code to make it compile, it's braking around this line:

auto val = what.getObject();

#include<iostream>
using namespace std;

class CUP{
    public:
        void whatsHappening(){}
};

class MUG{
    public:
        void whatsHappening(){}
};

class CupThrower{
    public:
        CUP cp;
        CUP getObject(){ return cp;}
};

class MugThrower{
    public:
        MUG mg;
        MUG getObject(){return mg;}
};

template <typename T> void whatsHappening(T what){

    auto val = what.getObject(); //DOES NOT COMPILE
    val.whatsHappening();
}

int main(){
    CupThrower ct;
    MugThrower mt;
    whatsHappening(ct);
    whatsHappening(mt);
    return 0;
}

i am using VS2008 to compile.


回答1:


Auto isn't supported in VS2008. Use VS2010 and later versions, or another compiler supporting this feature.




回答2:


Others have said that auto isn't in VC9, which is sort-of true. auto doesn't mean in the current C++ Standard what it means in C++0x. In the current Standard, it effectively means nothing useful. Long story short, you can't use auto the way you're trying to use it here.

But there is an alternative. In this code:

template <typename T> void whatsHappening(T what){

    auto val = what.getObject(); //DOES NOT COMPILE
    val.whatsHappening();
}

...the problem you're having is val is of an unknown type. If T is CupThrower, then getObject() returns a CUP. Likewise, for MugThrower, getObject() returns a MUG. The way your code is written, you have no way to know the type returned by getObject() based solely on the type of T. So the solution is to add a way to know it. Try this:

class CupThrower{
    public:
        typedef CUP ObjectType;
        ObjectType cp;
        ObjectType getObject(){ return cp;}
};

class MugThrower{
    public:
        typedef MUG ObjectType;
        ObjectType mg;
        ObjectType getObject(){return mg;}
};

Now the type returned by getObject() is part of the enclosing class. You can change your whatsHappening() function to use this information:

template <typename T> void whatsHappening(T what){

    T::ObjectType val = what.getObject(); //DOES COMPILE!
    val.whatsHappening();
}

And all is right with the world again.




回答3:


Auto is a feature only present in C++0x and, therefore, isn't enabled by default in most (if not all) the compilers. Have you used the appropriate options in your compiler to enable it?




回答4:


It doesn't compile because you're trying to deal with zero-sized non-function objects.

Edit: Works fine for me in VS2010.



来源:https://stackoverflow.com/questions/2924901/how-do-i-use-auto-in-c-c0x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!