gpt4 book ai didi

c++ - 两阶段名称查找 : PODs vs. 自定义类型

转载 作者:太空狗 更新时间:2023-10-29 19:52:34 29 4
gpt4 key购买 nike

编译运行代码时

#include <iostream>

struct A { A(int){} };

void foo( int ) { std::cout << "foo(int)" << std::endl; }

template< typename T >
struct S {
void bar() { foo( 5 ); }
void foobar() { T t = 5; foo(t); }
};

inline void foo( A ) { std::cout << "foo(A)" << std::endl; }
inline void foo( double ) { std::cout << "foo(double)" << std::endl; }

int main(int argc, char* argv[])
{
S<double> s0;
s0.bar();
s0.foobar();

std::cout << '\n';

S<A> s1;
s1.bar();
s1.foobar();
}

我得到了输出(使用 g++ 4.8、clang++ 3.2 或 icpc 13.1)

foo(int)
foo(int)

foo(int)
foo(A)

考虑到两阶段查找规则,虽然最后两行对我来说非常有意义,但我希望前两行是 foo(int) foo(double)

似乎在这种情况下,对于 foobar() 调用,foo() 在实例化之前被查找,这应该是不可能的。有什么提示吗?

最佳答案

T是模板参数,表达式t是类型相关的,因此 foo是函数调用中的从属名称 foo(t) . [temp.dep.candidate] 14.6.4.2/1 说:

For a function call that depends on a template parameter, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2, 3.4.3) except that:

  • For the part of the lookup using unqualified name lookup (3.4.1) or qualified name lookup (3.4.3), only function declarations from the template definition context are found.

  • For the part of the lookup using associated namespaces (3.4.2), only function declarations found in either the template definition context or the template instantiation context are found.

If the function name is an unqualified-id and the call would be ill-formed or would find a better match had the lookup within the associated namespaces considered all the function declarations with external linkage introduced in those namespaces in all translation units, not just considering those declarations found in the template definition and template instantiation contexts, then the program has undefined behavior.

实例化时S<double>::foobar , T显然是 double并且没有关联的 namespace 。所以唯一的声明foo将找到来自模板定义上下文 (void foo(int)) 的那些,如第一个项目符号中所述。

实例化时S<A>::foobar , TA . foo 的声明来自两个定义上下文

  • void foo(int)

    来自 A的关联命名空间(全局命名空间)被发现:

  • inline void foo( A ) { std::cout << "foo(A)" << std::endl; }

  • inline void foo( double ) { std::cout << "foo(double)" << std::endl; }

很明显void foo(A)是最佳匹配。

关于c++ - 两阶段名称查找 : PODs vs. 自定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23809774/

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