c++ 定义时绑定不合格的依赖名称(第一阶段0

omjgkv6w  于 2023-06-25  发布在  其他
关注(0)|答案(3)|浏览(134)

在“思考在c++”写的
澄清和总结:如果名称是依赖的,则在示例化时进行名称查找,除了对于不合格的依赖名称,在定义时也早期尝试正常的名称查找。
早期尝试的非限定依赖名称的确切示例是什么?我不知道为什么会有这个例外。先谢谢你了。
举例说明。

sg2wtvxw

sg2wtvxw1#

下面是一个例子:

  1. void f(int);
  2. template<typename T>
  3. void g(T x) {
  4. f(x); // Lookup of f here finds f(int)
  5. }
  6. void f(double);
  7. struct S {};
  8. void f(S);
  9. int main() {
  10. g(0); // Calls f(int) found through early lookup
  11. g(0.0); // Still calls f(int) since f(double) can't be found via ADL
  12. g(S()); // Calls f(S) found via ADL
  13. }

当调用f(x)时,候选函数是通过“正常”查找+在通过ADL关联的所有命名空间的作用域中查找找到的名称。正常的查找可以被认为是语义上发生在函数模板的声明中,而不是任何特定的专门化(g<int>g<double>g<S>)示例化。

展开查看全部
ylamdve6

ylamdve62#

带有依赖函数参数的非限定查找考虑:

  • 在模板定义处可见的函数(和变量),AND
  • 在模板示例化时通过ADL执行函数。

我认为这句话是想说,候选函数的列表可能在定义时构建(前半部分),然后在示例化期间的查找之前增加(后半部分)。

fgw7neuy

fgw7neuy3#

请考虑以下示例:

  1. template <typename T>
  2. struct foo_unqualified : T {
  3. foo_unqualified() {
  4. b<T>();
  5. }
  6. };

没有b,因此有error

  1. <source>:5:9: error: there are no arguments to 'b' that depend on a template parameter, so a declaration of 'b' must be available [-fpermissive]
  2. 5 | b<T>();
  3. | ^~~~

现在考虑这个例子:

  1. template <typename T>
  2. struct foo_qualified : T {
  3. foo_qualified() {
  4. foo_qualified::template b<T>();
  5. }
  6. };

这里还没有定义foo_qualified::b,这就是为什么这里的编译器需要关键字typename
只有在示例化时,才会真正查找名称:

  1. struct bar {
  2. template <typename T>
  3. void b(){}
  4. };
  5. struct no_bar {};
  6. int main() {
  7. foo_qualified<bar> f;
  8. foo_qualified<no_bar> f2; // error
  9. }

foo_qualified<bar>的示例化很好。foo_qualified<bar>继承自bar,现在有一个foo_qualified<bar>::b()模板。foo_qualified<no_bar>失败,因为查找失败(现在仅在示例化时)。
Live Demo

展开查看全部

相关问题