gpt4 book ai didi

c++ - 模板显式实例化如何工作以及何时工作?

转载 作者:行者123 更新时间:2023-12-03 06:49:44 26 4
gpt4 key购买 nike

这是 C++ 入门第 5 版的练习:
“练习 16.26:假设 NoDefault 是一个没有默认构造函数的类,我们可以显式实例化 vector<NoDefault> 吗?如果没有,为什么不呢?”
这是我的猜测:
是的,我们可以实例化它:

template <typename T>
class Foo
{
public:
void func(){cout << x_.value_ << endl;}
private:
T x_;
};

class Bar
{
public:
Bar(int x) : value_(x){}
void print(){}
private:
int value_{};
template <class T>
friend class Foo;
};

extern template class Foo<Bar>; // instantiation declaration
template class Foo<Bar>; // instantiation definition


int main()
{

// Foo<Bar> f;
}
代码工作正常,但如果我取消注释 main 中的行,我会按预期出现错误,因为 Bar不是默认构造的。
如果我使用相同的类 Bar作为 std::vector 的元素类型它不起作用:
extern template class vector<Bar>; // declaration ok
template class vector<Bar>; // instantiation: doesn't work?!
  • 那么为什么我的 Foo<Bar>实例化有效但无效 vector<Bar> ?
  • 在我看来,它在 vector<Bar> 中是合乎逻辑的。不工作,因为显式实例化定义实例化类模板的所有成员(即使是未使用的成员);在这个例子中,其中的 Foo<Bar> 的默认构造函数这意味着默认 ctor其元素类型 Bar ;后者不提供;毕竟Foo<Bar>()通常被声明为已删除的成员函数,因为 x_没有默认构造函数。所以我不知道为什么 Foo<Bar>定义有效?!谢谢你。
  • 最佳答案

    在标准中,[temp.explicit] 部分解释了显式实例化中发生的情况。特别是p12规定:

    An explicit instantiation definition that names a class template specialization explicitly instantiates the class template specialization and is an explicit instantiation definition of only those members that have been defined at the point of instantiation.


    现在, std::vector<T>有一个构造函数,它接受一个整数 n并用 n 初始化 vector 值初始化 T的。可以假设这个构造函数的定义在 <vector> 中的某处。 header (见 Why can templates only be implemented in the header file?)。所以 std::vector<Bar>的显式实例化定义将使用 T 实例化该构造函数= Bar .
    因为这是一个显式实例化,所以实例化的不仅是该构造函数的签名,还有它的整个主体。这必须在某处包括对 Bar 的默认构造函数的调用。 (可能作为它调用的另一个函数的一部分,此时也会被实例化),因此编译错误作为 std::vector<Bar> 的显式实例化定义的一部分发生。 .请注意,如果您隐式实例化 std::vector<Bar> ,它只会实例化(粗略地说)成员函数的签名。这就是为什么实际定义和使用 std::vector<Bar> 是合法的。对象,只要你不调用任何需要 Bar 默认构造函数的函数存在。 Foo<Bar>的显式实例化定义的原因成功的是,当 Foo<Bar>实例化后,编译器将其默认构造函数标记为已删除(只要存在不可默认构造的非静态成员,就会发生这种情况)。因此,它在任何时候都不会尝试编译任何需要 Bar 的默认构造函数的代码。 ,并且不会发生错误。

    关于c++ - 模板显式实例化如何工作以及何时工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64812138/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com