Returning multiple auto variable types in C++14

Asked

Viewed 35 times

1

I created a class, which has 4 attributes int valInt, float valFloat, double valDouble, bool valBool, and a method called getValue() of the auto type that returns the value according to another attribute called type, follows the code:

auto
ShareMemory::
getValue()
{
    switch (type) {
        case 0:
            return valInt;
        break;

        case 1:
            return valFloat;
        break;

        case 2:
            return valDouble;
        break;

        case 3:
            return valBool;
        break;

    }
}

When compiling, it accuses the following error in the line of return valFloat:

error: 'auto' in Return type deduced as 'float' here but deduced as 'int' in earlier Return statement.*

Is there any other way for me to return any of these values, without it pulling the type of the first Return?

1 answer

0


This looks like a classic case to use variant which allows values of different types to be stored in an object container and that you will disembowel afterwards and use as you wish. This has its usefulness, but almost always indicates that there is a design bad if you have control over the API, then see if you can’t do functions that return the specific value, almost always can. If you can’t leave it to consumer code to deal with, it’s not usually legal.

The variant was created to be a safer option for union that existed since C. As the variant was introduced only in C++17 I suggest switching to this version or newer. But if not, the union will be your solution. Only then it gets worse because you will have to turn around to identify the correct type that returned and use it the way you need. So the return would have to be something composed, could be for example a struct that has a field that is a tag type (can be any numerical value, an enumeration for example), and the union itself with the value. I explain this in How to assemble a list of generic objects in C?. You can also return a pair.

The auto You don’t do what you think you do. It does not mean that it accepts any type, only indicates that the compiler discovers alone which type will return, and in case he could not find out why not manually this is possible, is ambiguous.

In some situations the any may be interesting, but it’s even rarer. And there are other possible solutions, but should not be better.

Otherwise you can create your own variant, who knows how to copy what already exists in C++17. But only do so if you can’t even use a newer version. C++20 is there to help everyone.

Can help:

  • Thank you for your reply, you opened up a range of options, and a lot of things I didn’t know, I’ll study them, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.