V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
xss
V2EX  ›  问与答

C++成员模板函数,遇到个问题编译无法通过

  •  
  •   xss · Sep 11, 2016 · 2431 views
    This topic created in 3515 days ago, the information mentioned may be changed or developed.

    先看能编译通过的例子,如下在同一个文件 a.cpp 中:

    class A{
        public:
            template <typename T> void r(T& t){}
    };
    
    int main(){
        A objA;
        int i = 1;
        objA.r(i);
    }
    

    上面的例子使用 g++ a.cpp -o a 是可以编译通过的.

    现在,把 class A 拆分成.h 文件和.cpp 文件:

    a.h :

    class A{
        public :
            template <typename T> void r(T&);
    };
    

    a.cpp :

    #include "a.h"
    template <typename T> void A::r(T& t){}
    

    m.cpp :

    #include "a.h"
    int main(){
        A objA;
        int i = 1;
        objA.r(i);
    }
    

    然后编译:

    g++ -c a.cpp -o a.o

    g++ -c main.cpp -o main.o

    g++ a.o main.o -o final

    然后竟然报错了,说是 undefined void A::r<int>(int&)

    这是什么鬼,求解答.

    6 replies    2016-09-12 14:35:44 +08:00
    lifanxi
        1
    lifanxi  
       Sep 11, 2016   ❤️ 1
    现在的 g++还不能支持模板这么拆开写。需要把模板的声明和定义都写到头文件中。
    yangff
        2
    yangff  
       Sep 11, 2016   ❤️ 1
    从原理上来说吧,

    g++ -c main.cpp -o main.o 的时候, g++只能看到 A::r 的声明,而看不到定义,所以这个符号是没有编译进去的
    编译 g++ -c a.cpp -o a.o 的时候, g++看不到对 A::r 的展开方式,所以相当于什么都没有编译

    g++ a.o main.o -o final 的时候, main.o 要的符号, a.o 里就没有。

    以及, g++扫依赖是有顺序的,虽然和这个无关了
    skydiver
        3
    skydiver  
       Sep 11, 2016 via iPad
    模版类和方法的实现都要放在头文件里。
    skydiver
        4
    skydiver  
       Sep 11, 2016 via iPad
    多看看书吧少年…
    sfqtsh
        5
    sfqtsh  
       Sep 11, 2016 via Android   ❤️ 1
    你这问题《深入实践 C++模板编程》 1.3.1 节有讲~~
    messXD
        6
    messXD  
       Sep 12, 2016
    模版类的实现要放在头文件里。毕竟是模版,后面还要实例化。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6076 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 02:51 · PVG 10:51 · LAX 19:51 · JFK 22:51
    ♥ Do have faith in what you're doing.