这里如何将不完整类型用作向量的模板参数? [英] How can an incomplete type be used as a template parameter to vector here?

查看:87
本文介绍了这里如何将不完整类型用作向量的模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序是合法的,没什么:

TIL the following program is legal and whatnot:

#include <vector>

struct Bar;

struct Foo
{
    using BarVec = std::vector<Bar>::size_type;
};

struct Bar {};

int main()
{
   Foo f;
}

如何? Bar是不完整的类型,因此编译器无法知道std::vector<Bar>是什么,还是包含成员size_type,或者成员size_type是类型.

How? Bar is an incomplete type so the compiler has no way of knowing what std::vector<Bar> is, or that it contains a member size_type, or that the member size_type is a type.

我能提出的唯一解释是,任何假设的专业化(大概)必须已经在范围内,以使size_type的含义与基本"模板定义中给出的含义不同,并且size_type不是从属名称(这两个因素都会影响编译器的确定性).

The only explanation I can come up with is that any hypothetical specialisation would (presumably) have to already be in scope to cause size_type to take on a meaning different from that given in the "base" template definition, and size_type is not a dependent name (both factors contributing to the compiler's certainty).

这里的法律依据是什么?

What's the legal rationale here?

推荐答案

我认为这可能行得通,但从我的判断来看,这似乎是未定义的行为.根据C ++ 11标准草案17.6.4.8 [res.on.functions] :

I think in practice this may work but from what I can tell this looks like undefined behavior. From the draft C++11 standard 17.6.4.8 [res.on.functions]:

尤其是在以下情况下,效果是不确定的:

In particular, the effects are undefined in the following cases:

[...]

  • 如果在实例化模板组件时将不完整的类型(3.9)用作模板参数, 除非该组件特别允许.
  • if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

尽管实例化模板组件似乎不是一个明确定义的术语.

Although instantiating a template component does not seem like a well-defined term.

我是通过 LWG缺陷611 来到这里的添加:

I came to this via LWG defect 611 which added:

除非特别允许该组件使用

.

unless specifically allowed for the component.

到以上项目符号的末尾,因此现在显示为:

to the end of the bullet above so it now reads:

如果在实例化模板组件时将不完整的类型(3.9)用作模板参数,则除非该组件特别允许.

作为shared_ptr的例外,因为上述引用与20.6.6.2 [util.smartptr.shared]中的引用冲突:

as an exception for shared_ptr since the above quote conflicted with this quote from 20.6.6.2 [util.smartptr.shared]:

shared_ptr的模板参数T可能是不完整的类型.

The template parameter T of shared_ptr may be an incomplete type.

另请参见 N4371:对标准容器的最小不完整类型支持,修订版2 .

这篇关于这里如何将不完整类型用作向量的模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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