Skip to content

败犬日报 2024-12-19

1. std::conditional_t 会对未命中的 Type 做推导吗

会的。没有短路功能,如果是非良构的 Type 会报错。

可以用 constexpr if 来实现类似效果。

cpp
template <bool B>
auto my_conditional_impl() {
    if constexpr (B) {
        return std::type_identity<TypeA>{};
    } else {
        return std::type_identity<TypeB>{};
    }
}

template <bool B>
using my_conditional_t = decltype(my_conditional_impl<B>())::type;

另一种方法是模板类包一层:

cpp
template <typename>
struct good {};

template <>
struct good<int> {
    using type = int;
};

template <typename T>
struct LazyInit {
    using Type = typename good<T>::type;
};

int main() {
    using t =
        std::conditional_t<false, LazyInit<void>, int>;
}

2. ACMer の面试

https://www.zhihu.com/question/350973723/answer/14401855101


错误示范

面试官:“这题怎么做”

ACMer:“乱搞一下就出来了”

10分钟之后:“做法假了”


面试拿到一个问题先给一个朴素方案,然后分析它,指出不足,再给可能的改进思路,这才是很合格的面试表现。