2017-07-14 30 views
2

我做函數轉換整數或浮弦:如果constexpr和語法錯誤「類型」

#include <functional> 
#include <string> 
#include <iostream> 

template <typename From> 
inline std::string ToStr(const From& src) 
{ 
    constexpr bool isIntegral = std::is_integral<From>::value; 
    constexpr bool isFloat = std::is_floating_point<From>::value; 

    if constexpr (isIntegral) 
     return (std::_Integral_to_string<char>(src)); 
    else if (isFloat) 
     return (std::_Floating_to_string("%f", src)); 
} 

int main() 
{ 
    std::cout << ToStr(123); 
} 

我使用Visual Studio 2017年,我得到以下錯誤:
- 語法錯誤「 (第一if)
- 非法否則不匹配如果在線13(第二if)

我不知道如何解決它,任何想法?

+2

第四行沒有'type'。出示您的[MCVE]。 –

+0

高度相關:https://stackoverflow.com/questions/5246049/c11-static-assert-and-template-instantiation – Rakete1111

+0

@LightnessRacesinOrbit但是完全相同的代碼給出了這個錯誤。我很困惑,因爲你寫的那條線上沒有'type'。 – Condzi

回答

4

您正在運行15.2版本。

微軟在a blog post中表示,在15.3(預覽版2)中支持if constexpr

因此,請嘗試升級Visual Studio。

微軟很難清楚地管理他們軟件的不同版本,因爲他們希望每個人都「隨時」升級到最新版本。可悲的是,在這種情況下,當你需要知道什麼是什麼時,這並不是特別實用。