简体   繁体   English

了解c ++中的extern模板

[英]Understanding extern templates in c++

I am trying to understand extern templates, but i can't get it to work. 我试图了解外部模板,但我无法让它工作。 My goal is to compile some instanciations if Foo<> in a seperate compilation unit in order to save compilation time. 我的目标是在单独的编译单元中编译一些实例,如果Foo<> ,以节省编译时间。 In my code base, the template argument is a enum class , so in theory I am able to compile all instanciations in a compilation unit and link them with the rest of the project. 在我的代码库中,模板参数是一个enum class ,因此理论上我能够编译编译单元中的所有实例并将它们与项目的其余部分链接起来。

Here is a little example I come up with: 这是我想出的一个小例子:

//Foo.hpp
#pragma once

template <class T>
struct Foo {
    Foo();
    ~Foo();
};

extern template struct Foo<int>;

//Foo.cpp
#include "Foo.hpp"

template struct Foo<int>;

//main.cpp
#include <iostream>

#include "Foo.hpp"

int main(int argc, char **argv) {
   Foo<int> foo;

    return 0;
}

To for compilation i used a makefile, that boils down to this: 为了编译,我使用了一个makefile,归结为:

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

The output I get with gcc 7.1.1 and basically the same with clang 4.0.1 is: 我用gcc 7.1.1获得的输出与clang 4.0.1基本相同的是:

main.o: In function `main':
main.cpp:(.text+0x27): undefined reference to `Foo<int>::Foo()'
main.cpp:(.text+0x38): undefined reference to `Foo<int>::~Foo()'

My main question is, why is Foo<int>::Foo() and Foo<int>::~Foo() not compiled into Foo.o ? 我的主要问题是,为什么Foo<int>::Foo()Foo<int>::~Foo()没有编译成Foo.o

Because the constructor and destructor are not defined anywhere, you only declare them. 因为构造函数和析构函数没有在任何地方定义 ,所以只声明它们。 You correctly explicitly instantiate the template in the Foo.cpp file, but the functions are still not defined. 您正确地在Foo.cpp文件中显式实例化模板,但仍未定义函数。

If you are only going to use Foo<int> , then you can define the constructor and destructor in Foo.cpp , 如果你只想使用Foo<int> ,那么你可以在Foo.cpp定义构造函数和析构Foo.cpp

template<typename T>
Foo<T>::Foo(){...} // or = default

and

template<typename T>
Foo<T>::~Foo(){...}

and due to the fact that you explicitly instantiate the template in the Foo.cpp the linker will find the definition. 并且由于您在Foo.cpp显式实例化模板,链接器将找到该定义。 Otherwise, you need to provide the definition in the header file. 否则,您需要在头文件中提供定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM