Decltype (auto) with multiple return types using C ++ 14

I installed CTP-Nov2013-Compiler to get acquainted / experiment with some C ++ 14 (learning to read / read) features for VS 2013. I tried something like string for any POD type converter without using common methods which failed from -for an error (can't point to the correct beacuse error, as today I somehow got Visual Studio triggered when I try to create a program [CTP bug?]) 'return type is not the first return type.

An example of a 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 it a boolean error (except that no try-catch blocks are used to convert std::sto*

) or is it a syntax error?

Another problem I am having is that I had to implement the method in the header file (otherwise I got the error) and not in the .cpp file, is this a necessary / required function, for example for template functions?

+3


source to share


2 answers


You need to pass the compilation information as a template parameter.

And the information for inference must be compile-time information.



enum EType{
  eInt,
  eBool,
  eFloat,
  eString
};

template<EType type>
decltype(auto) convert(std::string texttoconvert);

template<>
decltype(auto) convert<eInt>(std::string texttoconvert) {
  return std::stoi(texttoconvert);
}
template<>
decltype(auto) convert<eFloat>(std::string texttoconvert) {
  return std::stof(texttoconvert);
}

struct Test {
  template<EType type>
  decltype(auto) SomeMethod(std::string texttoconvert) {
    return convert<type>(texttoconvert);
  }
};

int main() {
  Test t;
  float f = t.SomeMethod<eFloat>("3.14");
  std::cout << f << "\n";
}

      

live example .

0


source


This is a semantic error. auto

return type means that the method automatically inferred the return type, but the type is still the same for the entire method, it cannot be changed depending on the expression being called return

. Moreover, C ++ 14 requires all expressions to return

return the same type and disallow implicit conversions in this case.



+2


source







All Articles