c++ - "constexpr if"不支持别名使用?

标签 c++ c++17

我使用 gcc7.1 编译代码,但出现了一些编译错误:

错误:在“if”之前需要不合格的 id

错误:在“else”之前需要不合格的 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
    };
}

最佳答案

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

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

关于c++ - "constexpr if"不支持别名使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44118619/

相关文章:

c++ - 什么是 R6010 错误?

c++ - OpenCV-如何将RGB图像投影到日志(R/G)〜日志(B/G)空间?

c++ - 为什么 printf 的相同表达式的输出与 cout 不同?

c++ - 多线程事件系统

c++ - 特化 std::vector 的模板

c++ - 如何在同一个模板函数上专门化多个类型?

c++ - 不同编译器引用未知边界数组的奇怪行为

c++ - 一个只能由于整数溢出而失败的函数应该是 noexcept 吗?

c++ - 返回 shared_ptr 时的引用计数

c++ - 如何在编译时检查值和限制