c++ - 使用 C++14 的具有多个返回类型的 decltype(auto)

标签 c++ c++11 c++14 auto decltype

我安装了 CTP-Nov2013-Compiler 以熟悉/试验 VS 2013 的一些 C++14 功能(边做边学/阅读)。 我在没有使用因错误而失败的通用方法的情况下尝试了类似于任何 POD 类型转换器的字符串(无法拼写正确的错误,因为今天我以某种方式让 Visual Studio 在我尝试构建程序时崩溃 [CTP 错误?] ) '返回类型不是第一个返回类型'。

问题示例:

#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;
}

所以问题是,是逻辑类型的错误(除了不使用 try-catch-blocks 进行 std::sto* 转换)还是语法错误?

我遇到的另一个问题是,我必须在头文件中(否则我会出错)而不是在 .cpp 文件中实现该方法,这是像模板函数那样需要/必需的功能吗?

最佳答案

这是语义错误。 auto 返回类型表示方法已经自动推导出返回类型,但该类型对于整个方法仍然是一个类型,它不能根据调用的 return 表达式而改变。此外,C++14 要求所有 return 表达式返回相同的类型,并禁止在这种情况下进行隐式转换。

关于c++ - 使用 C++14 的具有多个返回类型的 decltype(auto),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31338845/

相关文章:

c++ - 使用 complex<double> 的函数式转换的模糊转换

C++:在文本文件中存储 char 数组时是否存储 Null?

c++ - 为什么 0x82 比 0x80 小?

c++ - openCV 存储文件错误 :

c++ - 使用 std::enable_if 保护复制构造函数

c++ - C++ 标准库中的模板模板参数?

c++ - 是否可以不在类头文件中包含类变量?

c++ - 为什么添加析构函数会更改此结构的复制构造函数行为?

c++ - 使用 decltype 的类型条件声明

c++ - 使用.inl内联文件的不完整向前声明