c++ - if constexpr 和 C4702(以及 C4100 和 C4715)

标签 c++ visual-c++ c++17 if-constexpr

有没有办法解决以下问题:

此代码生成 C4702 警告“无法访问的代码”(在带有 /std:c++17 的 VC++ 15.8 上)

template <typename T, typename VariantType>
inline bool MatchMonostate( VariantType& variant )
{
    SUPPRESS_C4100( variant );
    if constexpr ( std::is_same_v<T, std::monostate> )
    {
        variant = std::monostate();
        return true;
    }
    return false;  // !!! unreachable if the above is true !!! => C4702
}

为了抑制 C4100 的“未引用形式参数”警告,我已经在使用技巧了

#define SUPPRESS_C4100(x) ((void)x)

添加的简单思路

    else
    {
        return false;
    }

导致警告 C4715“并非所有控制路径都返回值”。

最佳答案

它是不可访问的,因为对于基于模板参数的模板的给定扩展,该函数将通过条件并返回 true 失败并返回 false。对于同一类型,不可能有任何一种情况。它本质上是扩展到

if (true) {
  return true;
}
return false; // Obviously will never happen

我会将其重写为只有一个返回语句。

template <typename T, typename VariantType>
inline bool MatchMonostate( VariantType& variant )
{
    SUPPRESS_C4100( variant );
    bool retval = false;
    if constexpr ( std::is_same_v<T, std::monostate> )
    {
        variant = std::monostate();
        retval = true;
    }
    return retval;
}

此外,在条件为真的情况下,变体不会未被使用。您可能希望将抑制警告(基本上变成 (void)variant)的那行移动到 else 语句。

关于c++ - if constexpr 和 C4702(以及 C4100 和 C4715),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52244640/

相关文章:

c++ - 是否可以一步在堆上创建一个 lambda?

c++ - 在类中存储指向 sqlite3 数据库的指针会引发段错误

c++ - 运行c++程序时vc++出现 fatal error

c++ - clang 和 gcc 中是否有 Visual C++ __declspec (属性声明属性)的替代方案?

visual-c++ - 设计一个适用于所有分辨率的MFC应用程序?

c++ - 为什么 `std::pmr::polymorphic_allocator` 不会在容器移动时传播?

c++ - 创建一个自定义整数,强制始终在指定范围内;如何克服整数溢出?

c++ - map 允许重复?

c++ - 模板类型的模板特化

c++ - 使用全局 std::array 引用作为模板参数时如何简化参数?