2017-05-22 28 views
1

我编译使用gcc7.1的代码,但是有一些编译错误:“constexpr if”不支持别名使用?

错误:预期不合格-ID之前 '如果'

错误:预期不合格-ID之前 '其他'

class Test 
{ 
    int a{1}; 
    string b{"test"}; 
    public: 
      template <int N> auto & get() 
      { 
      if constexpr (N==0) 
       return a; 
      else 
       return b; 
      } 
}; 

namespace std { 
    template<> struct tuple_size<Test> { static const int value = 2; }; 
    template<size_t N> struct tuple_element<N, Test> 
    { 
     if constexpr (N==0) //error: expected unqualified-id before ‘if’ 
      using type = int; 
     else     //error: expected unqualified-id before ‘else’ 
      using type = string; 
     //using type = conditional_t<N==0, int, string>; //this works 
    }; 
} 
+1

2013年前后有两个“静态if”提案可以实现这一点,但委员会拒绝了这一提案。 – TemplateRex

回答

3

一个constexpr if语句仍然是一个if语句,并且只能出现在可以使用if语句的上下文中。

这不包括类(模板)定义。

+0

@tc非常感谢! – camino

+1

我建议为此使用'std :: enable_if'或'std :: conditional' – Zereges