【问题标题】:When explicit template instantiation definition precedes explicit declaration, GCC and clang disagree当显式模板实例化定义在显式声明之前时,GCC 和 clang 不同意
【发布时间】:2015-10-02 04:32:50
【问题描述】:

见以下代码:

#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>();

而铿锵的那个是

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.

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

【问题讨论】:

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


    【解决方案1】:

    来自 [temp.explicit] / 11

    如果一个实体是同一翻译单元中显式实例化声明和显式实例化定义的主体,则定义应遵循声明。

    GCC 也应该对第一个示例给出错误。

    Related bug 从 2008 年开始,GCC 似乎在检测类错误时遇到问题,以下也漏掉了

    template <typename T> class f {};
    
    template class f<int>;
    extern template class f<int>;
    
    int main() {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2018-07-05
      相关资源
      最近更新 更多