LoudNPossiblyWrong
LoudNPossiblyWrong

Reputation: 3893

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

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.

Upvotes: 0

Views: 1312

Answers (4)

Puppy
Puppy

Reputation: 146910

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

Edit: Works fine for me in VS2010.

Upvotes: -2

cake
cake

Reputation: 1386

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?

Upvotes: 3

John Dibling
John Dibling

Reputation: 101456

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.

Upvotes: 3

Klaim
Klaim

Reputation: 69672

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

Upvotes: 11

Related Questions