【问题标题】:Trick to allow incomplete types in templates?在模板中允许不完整类型的技巧?
【发布时间】:2013-10-02 18:14:15
【问题描述】:

C++ STL 容器不允许使用不完整类型进行实例化;这是未定义的行为。

这是绕过该限制的有效“技巧”吗?还是这个技巧仍然有未定义的行为?

#include <vector>

template<template<class, class> class Vector = std::vector>
struct my_incomplete_vector
{
    struct Element;

    // Element is incomplete here, but does it matter anymore?
    typedef Vector<Element, std::allocator<Element> > type;

    struct Element { typename type::iterator value; };
};

int main()
{
    my_incomplete_vector<>::type v;
    v.resize(1);

    // this isn't normally possible without incomplete types
    v[0].value = v.begin();
    return 0;
}

【问题讨论】:

  • 您不会“将类型存储在容器中”。您将对象存储在容器中。
  • @KerrekSB:我修好了,但你的意思是?
  • 这个问题本来就很空洞......为什么天空是用砖头等制成的。
  • 我在这里没有看到任何不完整的类型。
  • @JohnSmith Element 用于定义type 时不完整。

标签: c++ stl incomplete-type


【解决方案1】:

这是未定义的行为。该标准要求类型是 如果它被用作模板的参数,则完成,在 模板实例化的点。和 my_incomplete_vector::Element使用时不完整 里面Element。在您真正做到之前不会出现任何问题 当然,实例化您的模板,但 g++ 无法编译 您的代码具有通常的调试选项 (-D_GLIBCXX_CONCEPT_CHECKS -D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC)。

【讨论】:

  • 这不是和struct T { T * p;}类似吗? T 不完整但可以定义指针/迭代器吗?
  • @JohnSmith 类型不一定要完整才能声明指向它的指针。
  • @JamesKanze:我不明白这里到底是什么未定义。在vector&lt;Element&gt; 的实例化点,Element 已经定义了,不是吗? vector&lt;Element&gt; 何时用不完整的 Element 类型实例化?
  • @Mehrdad 没有。vector&lt;Element&gt; 的实例化点在 Element 类内部,所以 Element 仍然是一个不完整的类型。
  • @Dilip 这是未定义行为的一种可能结果。委员会希望在 C++11 中对此进行诊断,但这取决于概念,由于各种原因没有进入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
相关资源
最近更新 更多