🔴 每种类型各生成一份,数给你看

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)函数模板里的 static 变量,每个实例化各有一个:

#include <iostream>
#include <string>

/* 函数模板里的 static 变量,**每个实例化各有一份**。
   这是「编译器替我生成了几份」唯一可移植的证据。 */
template <typename T>
int nth(const T &) { static int n = 0; return ++n; }

int main() {
    int i1 = 1, i2 = 2;
    double d = 1.5;
    std::string s = "ab";

    int a = nth(i1);      /* int 那一份:第 1 次 */
    int b = nth(i2);      /* 还是 int 那一份:第 2 次 */
    int c = nth(d);       /* double 是另一份:从 1 开始 */
    int e = nth(s);       /* string 又是一份:也从 1 开始 */

    std::cout << a << "/" << b << "/" << c << "/" << e << "\n";
    return 0;
}
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论