🔴 编译期就能定下来的事
同样这几步,中间要停几次
边停边干
先停一次
(这一段是 C++,用 g++ -std=c++17 -O0 -Wall 编译)这三个数都是**编译器算好的**,运行时一次判断都没有:
#include <iostream>
#include <type_traits>
/* C++ 这一路:类型和函数在**编译期**就定死了 */
template <typename T>
int decided_at_compile_time() { return std::is_integral_v<T> ? 1 : 0; }
int main() {
/* 这两个数是编译器算好的,运行时一次判断都没有 */
constexpr int a = 3 * 4;
std::cout << a << "/" << decided_at_compile_time<int>() << "/"
<< decided_at_compile_time<double>() << "\n";
return 0;
}
全部评论