gpt4 book ai didi

c++ - 指向具有外部链接的对象的指针作为非类型模板参数

转载 作者:太空狗 更新时间:2023-10-29 23:02:50 24 4
gpt4 key购买 nike

正如模板标准中所写,非类型模板参数之一可以是指向对象的指针。例如:

template <int* x>
void f()
{}

但是,在实例化期间提供参数时,只允许指向具有外部 链接的对象的指针。为什么?为什么标准不允许使用指向具有内部 链接的对象的指针来实例化非类型模板?

我在 StackOverflow 的其他主题中找到了一些解释,但我不太清楚:

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be: constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.

所以如果我在全局范围内有 static const int x = 10;,这个对象的地址是在编译时确定的吗?

另外我在评论解释中发现:

You don't know what the call-stack looks like at compile time. Before your function, there could've been called 10 other or 3 others or however many other, so the address on the stack, at which the string gets created can change from call to call. When you have an object with external linkage, its address is fixed during compilation/linkage.

如何在全局范围内更改定义的 static const int x = 10; 的地址?

了解幕后发生的事情会很棒。

最佳答案

在 C++11 中,要求放宽了(在 C++14 中有进一步的说明),现在 [temp.arg.nontype]/1 如下:

A template-argument for a non-type, non-template template-parameter shall be one of:
(...)
— a constant expression (5.19) that designates the address of a complete object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, where the id-expression is the name of an object or function, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference

所以在 C++11 中,这个编译,如你所愿:

template<int* i> void f(){};
static int x; // even without const
int main() {
f<&x>();
}

关于c++ - 指向具有外部链接的对象的指针作为非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27395773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com