【问题标题】:Why can't I have a reference to local variable as a non-type template parameter? [duplicate]为什么我不能将局部变量引用为非类型模板参数? [复制]
【发布时间】:2014-09-30 22:50:21
【问题描述】:

我不明白为什么会这样:

#include <iostream>

template<int& obj>
void foo() { obj = 42; }

int i;

int main()
{
    foo<i>();
    std::cout << i;
}

但事实并非如此:

#include <iostream>

template<int& obj>
void foo() { obj = 42; }

int main()
{
    int i;
    foo<i>();
    std::cout << i;
}
//error: the value of 'i' is not usable in a constant expression

【问题讨论】:

  • 为什么我的问题被否决了。它清晰简洁,是一个实际的 C++ 问题
  • 编译器实际上无法知道包含函数的堆栈帧在哪里。它甚至可能在多个函数调用中有所不同。 (尽管在本例中,重新输入 main 无论如何都会是 UB,但它可以是任何函数。)
  • 抱歉,更好的副本应该是:stackoverflow.com/questions/9218615/…

标签: c++ templates


【解决方案1】:

局部变量的地址是运行时特性,静态变量的地址是编译时特性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 2021-10-29
    • 2019-11-09
    • 1970-01-01
    • 2012-08-09
    相关资源
    最近更新 更多