Skip to content

败犬日报 2025-08-06

1. 有什么办法可以移除 C++ 的历史遗留问题

不可能的。找找有 break change 但活得好好的语言,大概率只能找到 python。

2. bool 变量分发到 bool 模板实参

简单的做法是宏,将 bool 传给 constexpr 变量:

cpp
#include <iostream>

#define DISPATCH_BOOL(condition, name, ...) \
    if (condition) {                        \
        constexpr bool name = true;         \
        (__VA_ARGS__)();                    \
    } else {                                \
        constexpr bool name = false;        \
        (__VA_ARGS__)();                    \
    }

template <bool Flag>
void foo() {
    printf("%d\n", Flag);
}

int main() {
    for (bool flag : {false, true}) {
        DISPATCH_BOOL(flag, Flag, [] { foo<Flag>(); });
    }
    return 0;
}

不用宏,用模板也是可以的:

cpp
#include <iostream>
#include <type_traits>

template <typename lambda_t>
auto dispatch_bool(bool condition, const lambda_t& lambda) {
    if (condition) {
        return lambda.template operator()<true>();
    } else {
        return lambda.template operator()<false>();
    }
}

template <bool Flag>
void foo() {
    printf("%d\n", Flag);
}

int main() {
    for (bool flag : {false, true}) {
        dispatch_bool(flag, []<bool Flag> { foo<Flag>(); });
    }
}

群友还给了 std::visit 的做法,支持多个 bool,不过看起来有点啰嗦:

cpp
#include <iostream>
#include <type_traits>
#include <variant>

std::variant<std::false_type, std::true_type> inline make_bool_variant(
    bool condition) {
    if (condition) {
        return std::true_type{};
    } else {
        return std::false_type{};
    }
}

int main() {
    for (auto [a, b, c] : {std::tuple{0, 0, 1}, std::tuple{1, 0, 1}}) {
        std::visit(
            [&](auto a, auto b, auto c) {
                printf("%d %d %d\n", decltype(a)::value, decltype(b)::value,
                       decltype(c)::value);
            },
            make_bool_variant(a), make_bool_variant(b), make_bool_variant(c));
    }
}