同时努力实现if constexpr与requires clause基于如果constexpr和要求,表达了即席概念检查面临着以下问题:
template<class P>
concept TuplePair = requires(P p) {
requires std::tuple_size<P>::value == 2;
std::get<0>(p);
std::get<1>(p);
};
void print(const auto& p) {
if constexpr( TuplePair<decltype(p)> ) {
std::cout << std::get<0>(p) << ", " << std::get<1>(p) << std::endl;
}
else {
std::cout << "else" << std::endl;
}
}
int main() {
// justifiably prints 'else':
print(std::make_tuple(3, 4, 5));
// prints 'else' even though this is a valid TuplePair:
print(std::make_tuple(1, 2));
}
Run Code Online (Sandbox Code Playgroud)
有什么问题if constexpr …
我对“原子约束”一章很好奇https://en.cppreference.com/w/cpp/language/constraints
它说
替换后 E 的类型必须恰好是 bool。不允许转换
和
f(0); // error: S<int>{} does not have type bool when checking #1,
// even though #2 is a better match
Run Code Online (Sandbox Code Playgroud)
哎哟。这意味着在使用 require 子句时没有 SFINAE 机制?这不是很糟糕吗?
因为我可以看到某些模板类型在遍历表达式后如何结果为 bool,但其他模板类型却看不到。现在我们又需要使用enable_if和东西了。痛得多?