Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decltype(auto) with multiple returning types using C++14

I installed the CTP-Nov2013-Compiler to get familiar/experiment with some C++14 features(learning by doing/reading) for VS 2013. I tried something like a string to any POD-type converter without using generic methods which failed due to the error (cannot spell the correct error beacuse since today I made somehow Visual Studio to crash whenever I try to build the program[CTP bug?]) 'return type is not of the first return type'.

An example of the problem:

#include <iostream>

using namespace std;

enum EType{
    eInt,
    eBool,
    eFloat,
    eString
}

class Test
{
    Test();
    virtual ~Test(){}

    decltype(auto) SomeMethod(std::string texttoconvert, EType type)
    {
        switch(type)
        {
            //convert to the specific type by using the C++11 stoi* functions and return it (for the example I'm not checking for failure in the conversion)
            case eInt: return std::stoi(texttoconvert);
            break;
            case eFloat: return std::stof(texttoconvert);
            break;
            ...
            default:
            break;
        }
    }


int main()
{
    Test hugo;
    auto lAuto=hugo.SomeMethod("1.234", eFloat);
    cout<<lAuto<<endl; //should return a float
    return 0;
}

So the question is, is the error of logical kind (except not using try-catch-blocks for the std::sto* conversion) or is it a syntax error?

Another problem I have, is that I had to implement the method in the header file(else I got an error) and not in the .cpp file, is this a wanted/necessary feature like for template functions?

like image 678
mbed_dev Avatar asked Feb 14 '26 16:02

mbed_dev


1 Answers

It's semantic error. auto return type means the method has automatically deduced return type but the type is still one for the whole method, it cannot change based on the invoked return expression. Moreover, C++14 requires that all return expressions return the same type and forbids implicit conversions in this case.

like image 85
StenSoft Avatar answered Feb 16 '26 05:02

StenSoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!