代码之家  ›  专栏  ›  技术社区  ›  Fureeish

我需要把constexpr放在else后面吗?

  •  29
  • Fureeish  · 技术社区  · 6 年前

    灵感来自 this answer ,我尝试复制和粘贴(并添加测试) main() )此代码:

    template<typename T>
    std::tuple<int, double> foo(T a) {
        if constexpr (std::is_same_v<int, T>)
            return {a, 0.0};
        else if (std::is_same_v<double, T>)
            return {0, a};
        else
            return {0, 0.0};
    }
    
    int main() {
        auto [x, y] = foo("");
        std::cout << x << " " << y;
    }
    

    T int ,我们要返回 [a, 0.0] . 如果 推断为 double ,我们要返回 [0, a] . 否则,我们要回去 [0, 0.0]

    主() 函数,我正在呼叫 foo 具有 const char* 参数,哪个 应该 x y 存在 0 不是这样的

    在试图编译它时,我遇到了一个奇怪的错误:

    错误:无法转换' {0, a} '从' <brace-enclosed initializer list> '收件人' std::tuple<int, double>

    我就像 std::is_same 启用 return {0, a} a 双重的 .

    cppreference 如果constexpr。在页面底部,上面 笔记 ,我们可以看到以下代码片段:

    extern int x; // no definition of x required
    int f() {
    if constexpr (true)
        return 0;
    else if (x)
        return x;
    else
        return -x;
    }
    

    我心想 .

    template<typename T>
    std::tuple<int, double> foo(T a) {
        if constexpr (std::is_same_v<int, T>)
            return {a, 0.0};
        else if constexpr (std::is_same_v<double, T>) // notice the additional constexpr here
            return {0, a};
        else
            return {0, 0.0};
    }
    
    int main() {
        auto [x, y] = foo("");
        std::cout << x << " " << y;
    }
    

    瞧!按预期编译和执行的代码。所以,我的问题是- constexpr if 中的语句 if-else 在这种情况下的陈述?

    1 回复  |  直到 5 年前
        1
  •  70
  •   Rakete1111    6 年前

    在这种情况下,是否需要在if-else块中的每个if语句后面加上constexpr?

    对。else if块 1 是一个谎言:),只有当块 1 . 编译器是这样看待代码的:

    if constexpr (std::is_same_v<int, T>)
        return {a, 0.0};
    else // {
        if (std::is_same_v<double, T>)
            return {0, a};
        else
            return {0, 0.0};
    // }
    

    else if (/*...*/) constexpr 是需要的。


    1 :“块”不是正确的术语。if是一个语句(带有可选的else部分)。一个街区是 { /*...*/ }