c++ - 当显式模板实例化定义先于显式声明时,GCC 和 clang 不同意

标签 c++ templates c++11 language-lawyer explicit-instantiation

请看下面的代码:

#include <vector>

template class std::vector<int>;
extern template class std::vector<int>;

int main() {}

虽然 GCC 5.2 编译正常,但 clang 3.6 给出了以下错误消息:

main.cpp:4:28: error: explicit instantiation declaration (with 'extern') follows explicit instantiation definition (without 'extern')
extern template class std::vector<int>
                           ^
main.cpp:3:21: note: explicit instantiation definition is here
template class std::vector<int>
                    ^
1 error generated.

还是对于下面的代码

template <typename T>
void f() {}

template void f<int>();
extern template void f<int>();

int main() {}

GCC 和 clang 都出错了。 GCC 的消息是

main.cpp:5:29: error: duplicate explicit instantiation of 'void f() [with T = int]' [-fpermissive]
 extern template void f<int>();

clang 的那个是

main.cpp:5:22: error: explicit instantiation declaration (with 'extern') follows explicit instantiation definition (without 'extern')
extern template void f<int>();
                     ^
main.cpp:4:15: note: explicit instantiation definition is here
template void f<int>();
              ^
1 error generated.

这两个家伙是怎么回事?标准是否禁止显式模板实例化声明之前有显式定义?这对我来说没什么意义。毕竟,先定义再声明有什么害处呢?想想非模板函数的情况。

最佳答案

来自 [temp.explicit]/11

If an entity is the subject of both an explicit instantiation declaration and an explicit instantiation definition in the same translation unit, the definition shall follow the declaration.

GCC 也应该为第一个示例提供错误。

相关bug从 2008 年开始,GCC 似乎在检测类错误时出现问题,以下内容也被遗漏

template <typename T> class f {};

template class f<int>;
extern template class f<int>;

int main() {}

关于c++ - 当显式模板实例化定义先于显式声明时,GCC 和 clang 不同意,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32900588/

相关文章:

c++ - 获取 ActiveX 窗口句柄

c++ - 我如何使用 libavfilter 在我的视频播放器软件中去隔行帧

c++ - QT5中的TableView不显示MYSQL数据,只显示空行

c++ - gcc 编译带有大量模板参数的模板类时出错

php - 在 WooCommerce 的“我的帐户”>“下载”部分更改列名称

c# - x64 上的文件时间

c++ - 错误 : Illegal zero sized array

c++ - 理解 c++11 右值、 move 语义和性能

c++11 - 如何将 static_cast<T> 作为函数传递?

c++ - 在这种情况下 unique_ptr 的行为应该是什么?