[英]decltype(auto) with multiple returning types using C++14
我安裝了CTP-Nov2013-Compiler來熟悉/試驗VS 2013的一些C ++ 14特性(通過實踐/閱讀學習)。我嘗試了類似於任何POD類型轉換器的字符串,而沒有使用失敗的通用方法錯誤(無法拼寫正確的錯誤,因為今天我以某種方式使Visual Studio崩潰,每當我嘗試構建程序[CTP bug?])'返回類型不是第一個返回類型'。
問題的一個例子:
#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
表達式返回相同的類型,並禁止在這種情況下進行隱式轉換。
您需要將編譯時信息作為模板參數傳遞。
並且類型確定信息必須是編譯時信息。
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";
}
實例 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.