今天,有人向我提供了以下形式的代码:
#include <iostream>
namespace example {
template <typename T>
T variable_template = T(42);
}
int main() {
example::variable_template<int> = 10;
std::cout << example::variable_template<int> << std::endl;
}
你可以看到它在这里运行:http://coliru.stacked-crooked.com/a/3a786c42b5204b0a
我希望此代码打印 42,因为 10 似乎分配给了一个临时值。在命名空间内,模板只是一个声明(不是实例化),因此在命名空间内没有要改变的数据。尽管如此,它让我感到惊讶并打印了 10。
我还希望在分配给临时对象时收到警告,但那也没有发生。
这是未定义的行为,是我对模板的理解存在缺陷,还是其他原因?
最佳答案
Inside the namespace, there template is only a declaration (not an instantation), so there's no data to mutate inside of the namespace.
不是这样的!
[C++14: 14.7.2/6]:
An explicit instantiation of a class, function template, or variable template specialization is placed in the namespace in which the template is defined. [..]
当你有一个类模板时 Foo
, 并引用一个实例化(比如 Foo<int>
),该实例化就像一个普通类一样存在,具有与模板相同的作用域。
变量模板没有什么不同。当您引用 example::variable_template<int>
,您将该变量“添加”到包含模板的范围。
您的命名空间 example
然后包含一个名为 variable_template<int>
的变量.
I would have also expected a warning on the assignment to a temporary, but that didn't happen either.
除了 T(42)
之外,这里没有临时对象.
关于c++ - 变量模板可以变异吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528905/