gpt4 book ai didi

c++ - 关于模板实例化点的一些问题

转载 作者:行者123 更新时间:2023-12-03 18:49:11 25 4
gpt4 key购买 nike

首先是一些标准的引用段落

If a template specialization X is referenced in a context that depends on a template-parameter of some surrounding template Y, the given point of instantation depends on the point of instantation of Y.
If X is a function template specialization, the point of instantiation is that of Y.
If X is a class template specialization, the point of instantiation is immediately before the point of instantiation of Y.

Otherwise, the given point of instantiation is tied to the location of the namespace scope declaration/definition (D) which contains the statement referring to X.
If X is a function template specialization, the point of instantiation is immediately after D.
If X is a class template specialization, the point of instantiation is immediately before D.

这里是一些代码

#include <iostream>
template<int N>
struct state {
friend auto call(state<N>);
};
template<int N>
struct add_state {
friend auto call(state<N>) {
return N;
}
};
template<typename T, int N>
T show() {
add_state<N> d;
return T{};
}
template<typename T,int N>
class data {
public:
T c = show<T,N>();
};
#1,#3,#2
int main() {
data<int, 0> t;
call(state<0>{});
}

所以,根据上面的规则,在实例化类data<int, 0>的时候,则实例化点位于#1。

然后show<T,N>取决于模板类数据的模板参数。所以实例化点为show<int,0>在#2。

然后add_state<N>取决于模板函数显示的模板参数。所以根据规则,实例化点为add_state<0>在#3。

在 #3 auto call(state<0>)已定义,call(state<0>{})应该是链接但是实际上编译器报错如下:

clang :

main.cpp:24:2: error: function 'call' with deduced return type cannot be used before it is defined
call(state<0>{});
^
main.cpp:4:14: note: 'call' declared here
friend auto call(state<N>);
^
1 error generated.

g++:

main.cpp: In function ‘int main()’:
main.cpp:24:17: error: use of ‘auto call(state<0>)’ before deduction of ‘auto’
call(state<0>{});
^

为什么?我对实例化点的理解是否有一些错误?如果不是,为什么编译器会报告这些错误?

最佳答案

根据 [temp.inst]/2.1 ,当一个类模板被隐式实例化时,只有 friend 的声明被实例化:

The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions, default arguments, or noexcept-specifiers of the class member functions, member classes, scoped member enumerations, static data members, member templates, and friends;

所以在 #3 auto call(state<N>)仅被声明。此外,通过普通的非限定名称查找找不到此声明。

尽管如此,我不认为它会使您的代码格式错误。您的代码太奇怪了,标准委员会成员或编译器实现者可能从未考虑过这种情况:通常在类中定义内联友元函数,使友元函数通过 ADL(参数相关名称查找)可见。这当然也是编译器的异常(exception)。

所以在 call(state<0>{})里面main , call 的声明由 ADL 在 state 的定义中找到并且编译器只是不考虑在某种不相关的类 add_state 中寻找此函数的潜在定义.所以它无法推断出 auto .

关于c++ - 关于模板实例化点的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58450676/

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