【问题标题】:Reference or pointer to std::vector of incomplete type指向不完整类型的 std::vector 的引用或指针
【发布时间】:2016-03-15 08:32:46
【问题描述】:

此处已回答:How can an incomplete type be used as a template parameter to vector here? 在实例化模板组件时使用不完整类型作为模板参数可能会导致未定义的行为。但是,当我们只有指向具有不完整类型的模板组件的指针/引用作为参数时,该规则是否成立?这种情况下是否也会发生实例化?

例如:

// SomeAlgoInterface.hpp

#include <vector> 

struct Result; // forward declaration

class SomeAlgoInterface
{
  public:

   virtual ~SomeAlgoInterface() = default; 

  public:

    // the following line is definitely OK, ...
    virtual void f1(const Result & result) = 0; 

    // ... but I'm not quite sure about the following one
    virtual void f2(const std::vector<Result> & results) = 0; 
};

换句话说,上面的代码是否有效?

【问题讨论】:

  • 根据[temp.inst]/4中的例子,这个声明不会导致实例化

标签: c++ templates c++11 vector


【解决方案1】:

声明是正确的,只要你不调用f2

如果你不调用f2,编译器不需要知道Result类的内部。声明中没有存储分配。

如果某个编译单元调用f2,你需要提供Result类的完整类型,或者你需要另一个引用参数来调用f2

void another_f(SomeAlgoInterface& i, std::vector<Result>& results)
{
    i.f2(results);  
}

【讨论】:

  • 如果你仍然不使用类中的任何东西,我不太确定调用它是否需要实例化,例如在您的示例中,如果 i.f2 也通过引用接受了向量
猜你喜欢
  • 2016-02-19
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多