为什么不从void函数模板返回编译器错误? [英] Why don't I get compiler errors from returning from a void function template?

查看:102
本文介绍了为什么不从void函数模板返回编译器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑:

void f() {
    return 5;
}

上述操作会引发错误。但为什么不这样呢?:

The above will raise errors. But why not this?:

template <typename = void> void f() {
    return 0;
}

我正在使用gcc-4.5.1编译。为什么它使用模板,使我不会收到错误从做一个非模板函数执行相同的非法返回语句有所不同?我得到的唯一的挫折是,我不能调用函数(即 f()),而不获得:

I'm compiling with gcc-4.5.1. Why does it make a difference using templates such that I wouldn't receive errors from doing the same illegal return statement as a non-template function?. The only setback I get is that I can't call the function (i.e f()) without getting:


错误:在函数中返回void的返回语句

但是,我能为void函数模板定义一个return语句的原因是什么?

But still, what could be the reason that I am able to define a return statement for a void function template?

这里是代码我有:

template <typename = void> void f() {
    return 0;
}

// pass

int main() {



}

上述代码将会通过,尽管在一个返回void的函数中可能是非法的return语句。

The above code will pass despite a presumably illegal return statement in a function returning void.

推荐答案

这是一个执行质量问题。标准中的特定引用是:

This is a quality of implementation issue. The particular quote from the standard would be:


14.6 / 8 [...]如果没有为模板定义生成有效的专业化,并且该模板未实例化,模板定义是错误的,无需诊断。 [...]

14.6/8 [...] If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required. [...]

也就是说,您的程序是不成形的,因为该模板不能用于生成任何 / em>专业化,但编译器不需要诊断这一点。在稍后的时间实例化模板时,编译器必须生成专门化,专门化无效并且编译器提示。

That is, your program is ill formed because that template cannot be used to generate any valid specialization, but the compiler is not required to diagnose this. When at a later time you instantiate the template, the compiler must generate the specialization, that specialization is not valid and the compiler complains.

您不会遇到错误模板定义,因为编译器遵循无需诊断所需的路径,即忽略问题,直到它不再在实例化中忽略它。

You don't get an error in the template definition because the compiler is following the no diagnostic required path, i.e. ignoring the problem until it can no longer ignore it in the instantiation.

这篇关于为什么不从void函数模板返回编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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