【发布时间】: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