调用模板函数时出现意外输出 [英] Unexpected output on calling template function

查看:82
本文介绍了调用模板函数时出现意外输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The below code is part of a cpp quiz that I was going through :

#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

I fail to understand why the output turns out to be TS. I expected it to be SS

编译器:gcc版本4.8.5 20150623

Compiler : gcc version 4.8.5 20150623

推荐答案

§14.6¶9指出:当查找名称中使用的名称声明时, 模板定义,使用常规查找规则(第3.4.1节,第3.4.2节) 用于非依赖性名称.根据模板查找名称 参数被推迟到知道实际的模板参数为止 (第14.6.2节)."

§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的第一次调用是一个非依赖调用,因此在定义函数模板时会对其进行查找.如果是第二个调用,则将其推迟到实例化模板之前,因为它取决于模板参数.

The first call to foo is a non-dependent call, so it is looked up at the time of definition of the function template. In case of the second call, it is deferred until the template is instantiated because it depends on a template parameter.

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)尚不存在,并且不是候选对象.

When foo is being looked up at the time of definition of the function template, the only version of foo that exists is the templated foo(T). Specifically, foo(S) does not exist yet, and is not a candidate.

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

Interesting thing would be check what your code outputs in Visual Studio, I think in that case it would output the SS that you expected.

答案来源: CPPQuiz .

不幸的是,由于我无法再次找到答案,因此我不再具有答案的确切链接.

Unfortunately, I do not have the exact link of the answer anymore since I am not able to find it again.

这篇关于调用模板函数时出现意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆