代码之家  ›  专栏  ›  技术社区  ›  Shahbaz Martin York

cpp文件中模板成员的显式实例化不会生成符号(即链接错误)

  •  0
  • Shahbaz Martin York  · 技术社区  · 3 年前

    以以下示例为例:

    // A.h
    class A
    {
    public:
        int v = 2;
    
        template <typename T>
        int f(T t);
    };
    
    // A.cpp
    #include "A.h"
    
    template <typename T>
    int A::f(T t)
    {
        return v + t;
    }
    
    template <>
    int A::f<int>(int t);
    
    // main.cpp
    #include <stdio.h>
    
    #include "A.h"
    
    int main()
    {
        A a;
        printf("%d\n", a.f(3));
        return 0;
    }
    

    使用构建时 clang -std=c++14 (或g++),我得到以下错误:

    main.cpp:8: undefined reference to `int A::f<int>(int)'
    

    的确 nm A.o 没有显示任何符号。为什么的显式实例化没有 A::f<int> 在…内 A.cpp 实际实例化函数?

    0 回复  |  直到 3 年前
        1
  •  1
  •   mksteve    3 年前

    我想@JaMiT得到了答案。

    template <> int A::f<int>(int t)
    {
        // full specialization of templated thing
    }
    

    是完全专业化的。

    template <> int A::f<int>(int t);
    

    是一个声明,表明存在这样的专门化,但没有提供定义。

    你想要的表格是

     template int A::f<int>(int t);
    

    它是成员函数的实例化。