小编B.M*_*.M.的帖子

为什么在这种情况下需要always_false_v?

我用来std::variant指定项目中的实体可能具有的属性类型,并从 cppreference 中偶然发现了以下代码:

std::visit([](auto&& arg)
        {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, int>)
                std::cout << "int with value " << arg << '\n';
            else if constexpr (std::is_same_v<T, long>)
                std::cout << "long with value " << arg << '\n';
            else if constexpr (std::is_same_v<T, double>)
                std::cout << "double with value " << arg << '\n';
            else if constexpr (std::is_same_v<T, std::string>)
                std::cout << "std::string with value " << std::quoted(arg) << '\n';
            else 
                static_assert(always_false_v<T>, "non-exhaustive visitor!");
        }, w);
Run Code Online (Sandbox Code Playgroud)

always_false_v定义为 …

c++ c++17 if-constexpr

5
推荐指数
1
解决办法
415
查看次数

标签 统计

c++ ×1

c++17 ×1

if-constexpr ×1