Simplify Code with “if constexpr” in C++17
Introduction
程序设计需要不断地做抉择,抉择便需用到逻辑分派。
Modern C++ 中,有多种方式完成这个任务,例如 Run-time if,Tag dispatching,SFINAE,Partial Specialization 等等。这些方式分为运行期分派和编译期分派,分派的条件称为约束。设计是为了厉行约束,理想上,能在编译期强制表现的约束就应提升到编译期完成。
C++17 又增加了一种编译期方式 Compile-time if;C++20 中,又增加了 Concepts。
本篇就来总结一下各种方式的用法异同(Concepts见下篇)。
Run-time if
运行期 if 就是运行时期才会执行的分支语句,例如:
template <typename T>
void foo(const T& val)
{
if(std::is_integral<T>::value) {
std::cout << "integral\n";
} else {
std::cout <<… Continue Reading