不完整的类型如何用作 vector 的模板参数?
How can an incomplete type be used as a template parameter to vector here?
直到以下程序是合法的等等:
#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
是一个类型。
我能想到的唯一解释是,任何假设的专业化(大概)必须已经在范围内才能导致 size_type
具有与 [=25= 中给出的含义不同的含义] 模板定义,并且 size_type
不是从属名称(这两个因素都有助于编译器的确定性)。
这里的法律依据是什么?
我认为这在实践中可能有效,但据我所知,这看起来像是未定义的行为。来自 C++11 标准草案 17.6.4.8
[res.on.functions]:
In particular, the effects are undefined in the following cases:
[...]
- if an incomplete type (3.9) is used as a template argument when instantiating a template component,
unless specifically allowed for that component.
虽然实例化模板组件似乎不是一个定义明确的术语。
我是通过 LWG defect 611 找到这个的,其中添加了:
unless specifically allowed for the component.
到上面项目符号的末尾,现在显示为:
if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for the component.
作为 shared_ptr
的例外,因为上述引用与 20.6.6.2
[util.smartptr.shared] 中的引用冲突:
The template parameter T of shared_ptr may be an incomplete type.
另见 N4371: Minimal incomplete type support for standard containers, revision 2。
直到以下程序是合法的等等:
#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
是一个类型。
我能想到的唯一解释是,任何假设的专业化(大概)必须已经在范围内才能导致 size_type
具有与 [=25= 中给出的含义不同的含义] 模板定义,并且 size_type
不是从属名称(这两个因素都有助于编译器的确定性)。
这里的法律依据是什么?
我认为这在实践中可能有效,但据我所知,这看起来像是未定义的行为。来自 C++11 标准草案 17.6.4.8
[res.on.functions]:
In particular, the effects are undefined in the following cases:
[...]
- if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.
虽然实例化模板组件似乎不是一个定义明确的术语。
我是通过 LWG defect 611 找到这个的,其中添加了:
unless specifically allowed for the component.
到上面项目符号的末尾,现在显示为:
if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for the component.
作为 shared_ptr
的例外,因为上述引用与 20.6.6.2
[util.smartptr.shared] 中的引用冲突:
The template parameter T of shared_ptr may be an incomplete type.
另见 N4371: Minimal incomplete type support for standard containers, revision 2。