yki*_*kim 7 c++ templates vector c++11
正如在这里所回答的:如何将不完整类型用作向量的模板参数?在实例化模板组件时使用不完整类型作为模板参数可能导致未定义的行为.但是当我们只有指向不完全类型的模板组件的指针/引用作为参数时,该规则是否成立?在这种情况下,实例也会发生吗?
例如:
// 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;
};
Run Code Online (Sandbox Code Playgroud)
换句话说,上面的代码是否有效?
只要您不调用 ,该声明就是正确的f2。
Result如果你不调用 ,编译器不需要知道类的内部f2。声明中没有存储分配。
如果某些编译单元调用f2,您需要提供Result类的完整类型,或者您需要另一个引用参数来调用f2:
void another_f(SomeAlgoInterface& i, std::vector<Result>& results)
{
i.f2(results);
}
Run Code Online (Sandbox Code Playgroud)