为什么这段代码不会产生编译错误? [英] Why doesn't this code generate compilation errors?

查看:32
本文介绍了为什么这段代码不会产生编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

template<class T>
void foo()
{
    M
}

除非我实例化它,否则 Visual C++ 不会告诉我上面的代码包含错误.这是为什么?

Unless I instantiate it, Visual C++ does not tell me the above code contains error(s). Why is this?

推荐答案

C++ 标准包含对此问题的非正式描述,该描述描述了我认为是一个很好的指导方针,并被许多人认为是规范.

The C++ Standard contains an informal description of this matter which describes what I think would be a good guideline and is taken by many people to be the normative requirement implied by the specification.

然而,实现可以指向标准的规范部分,允许它们比明显"规则似乎陈述的更进一步.我将在下面描述这一点.

However, implementations can point to normative parts of the Standard that allow them to go further than what the "obvious" rules seem to state. I will describe this below.

标准允许实现在模板定义被实例化之前不检查它们.它没有给出模板定义"何时实际上应该是模板定义的正式描述,但通常的实现是做括号平衡"/括号平衡"的形式:从最外层的括号开始定义的主体,数到最后一个右括号.两者之间的所有内容都被忽略.

The Standard allows an implementation not to check template definitions until they are instantiated. It doesn't give a formal description as to when a "template definition" is actually supposed to be a template definition, but the usual implementation is to do forms of "brace balancing" / "parens balancing": Start from the outermost brace of the definition's body, count until you hit the last closing brace. Everything in between is ignored.

我想标准中的一个例子进一步阐明了这一点

I suppose an example from the Standard clarifies this further

template<class T> class X {
  // ... (omitted) ...
  void g(T t) {
    +; // may be diagnosed even if X::g is not instantiated
  }
};

因此早期诊断模板定义中的语法或语义错误是一种实现质量".

So early diagnosis of syntax or semantic errors in template definitions is a "quality of implementations".

这些规则具有无需诊断"的品质.值得注意的是,这些规则的实现被授予不诊断格式错误的模板定义即使模板被实例化的许可,尽管标准的非规范性说明是这样说的.如果违反了不需要诊断的任何规则,则实现可以自由地对整个程序做任何想做的事情.

These rules are of the quality "no diagnostic required". Noteworthy, implementations by these rule are granted the license not to diagnose ill-formed template definitions even if the template is instantiated, despite what the non-normative note of the Standard says. If any rule for which no diagnostic is required is violated, an implementation is free to do whatever it wants with the entire program.

还应该注意的是,没有语法错误的模板定义",因为这个术语是由语法本身定义的.一个孤独的 + 将整个封闭的上下文呈现为一些无意义的标记汤.

It should be noted that also, there is no syntactically ill-formed "template definition", because this very term is defined by the syntax itself. A lonely + renders the whole enclosing context to be some soup of nonsensical tokens.

最后但并非最不重要的一点是,委员会知道这些漏洞",但据我所知,到目前为止,没有多数人可以改变这一点.

Last but not least, the committee knows about these "loopholes", but there was no majority to change this so far, as far as I know.

这篇关于为什么这段代码不会产生编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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