【问题标题】:Why does extern template instantiation not work on move-only types?为什么 extern 模板实例化不适用于仅移动类型?
【发布时间】:2022-01-16 04:36:21
【问题描述】:

下面的代码就可以了:

#include <memory>
#include <vector>

extern template class std::vector<int>;
template class std::vector<int>; // ok on copyable types

int main()
{
    [[maybe_unused]] auto v1 = std::vector<int>{}; // ok
    [[maybe_unused]] auto v2 = std::vector<std::unique_ptr<int>>{}; // ok   
}

但是,下面编译失败:

#include <memory>
#include <vector>

extern template class std::vector<std::unique_ptr<int>>;
template class std::vector<std::unique_ptr<int>>; // error on move-only types

int main()
{
    [[maybe_unused]] auto v1 = std::vector<int>{};
    [[maybe_unused]] auto v2 = std::vector<std::unique_ptr<int>>{};    
}

见:https://godbolt.org/z/8qe94oGx5

为什么 extern 模板实例化不适用于仅移动类型?

【问题讨论】:

  • 您遇到了哪个错误?第二行是干什么用的?
  • 链接更新了,错误信息在里面。
  • 请问您为什么在代码中将 extern 和 template 行放在 main 之前? include 和 main 应该足够了
  • 为了更快的编译速度。 @PepijnKramer
  • 在这个例子中闻起来像过早的优化。 stackoverflow.com/questions/8130602/using-extern-template-c11

标签: c++ performance templates c++20 extern


【解决方案1】:

显式实例化定义(又名template class ...)将实例化所有成员函数(本身没有模板化)。

除其他外,它会尝试实例化向量的复制构造函数(以及其他需要可复制性的函数),并且会因为明显的原因而失败。

requires 可以阻止它,但std::vector 不使用它。有趣的是,在这种情况下,Clang 忽略了requires,所以I reported a bug。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多