gpt4 book ai didi

c++ - 调用模板函数时的意外输出

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:36 24 4
gpt4 key购买 nike

下面的代码是我正在经历的 cpp 测验的一部分:

#include <iostream>

template<typename T>
void foo(T)
{
std::cout << "T" << std::endl;;
}

struct S
{
};

template<typename T>
void call_foo(T t)
{
foo(S());
foo(t);
}

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

int main()
{
call_foo(S());
}

我不明白为什么输出结果是TS。我希望它是 SS

Compiler : gcc version 4.8.5 20150623

最佳答案

§14.6¶9 states: "When looking for the declaration of a name used in a template definition, the usual lookup rules (§3.4.1, §3.4.2) are used for non-dependent names. The lookup of names dependent on the template parameters is postponed until the actual template argument is known (§14.6.2)."

foo的第一次调用是非依赖调用,所以在函数模板定义时查找。在第二次调用的情况下,它被推迟到模板被实例化,因为它取决于模板参数。

template<typename T> void call_foo_function(T t)
{
foo(S()); // Independent, looks up foo now.
foo(t); // Dependent, looks up foo later.
}

当在定义函数模板时查找 foo 时,唯一存在的 foo 版本是模板化的 foo(T)。具体来说,foo(S) 还不存在,也不是候选对象。

有趣的是检查您的代码在 Visual Studio 中输出的内容,我认为在这种情况下它会输出您期望的 SS

答案来源:CPPQuiz .

不幸的是,我没有答案的确切链接了,因为我无法再次找到它。

关于c++ - 调用模板函数时的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49643164/

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