x43*_*2ph 3 c++ std variadic-templates c++17 if-constexpr
从cppreference.com上的描述中,我得到的印象是std :: disjunction旨在使我在编译时短路,因此我可以这样使用它:
#include <type_traits>
#include <iostream>
template<nullptr_t null = nullptr>
constexpr bool does_not_compile() {
    static_assert(null != nullptr);
    return false;
}
void hello_world () {
    if constexpr (std::disjunction_v<std::true_type, std::bool_constant<does_not_compile()>>) {
        std::cout << "Hello World!" << std::endl;
    }
}
但是,这不会编译,在上述static_assert不会触发的意义上,std :: disjunction不会短路(实时示例)。
但是,那是什么意思呢?这不是||的通常行为 在运行时,因为必须在编译时知道std :: disjunction的类型,这取决于其值。
您可以在链接到的页面上找到说明:
脱节短路:如果有一个模板类型参数
Bi用bool(Bi::value) != false,然后实例disjunction<B1, ..., BN>::value不需要的实例Bj::value对于j>我
短路行为涉及value每个参数类型的成员,而不是参数类型本身。您不能在不知道模板参数的情况下实例化模板。使用std::disjunction<…>通常需要实例化。在你的例子中
std::disjunction_v<std::true_type, std::bool_constant<does_not_compile()>>
编译器仍然必须实例化,std::bool_constant<does_not_compile()>以便它知道整体std::disjunction<…>结果(如您自己指出的那样)。可以保证的是不会实例化std::bool_constant<does_not_compile()>::value……