[英]Understanding extern templates in c++
我試圖了解外部模板,但我無法讓它工作。 我的目標是在單獨的編譯單元中編譯一些實例,如果Foo<>
,以節省編譯時間。 在我的代碼庫中,模板參數是一個enum class
,因此理論上我能夠編譯編譯單元中的所有實例並將它們與項目的其余部分鏈接起來。
這是我想出的一個小例子:
//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;
}
為了編譯,我使用了一個makefile,歸結為:
g++ -c ../Foo.cpp ../main.cpp
g++ Foo.o main.o
我用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()'
我的主要問題是,為什么Foo<int>::Foo()
和Foo<int>::~Foo()
沒有編譯成Foo.o
?
因為構造函數和析構函數沒有在任何地方定義 ,所以只聲明它們。 您正確地在Foo.cpp
文件中顯式實例化模板,但仍未定義函數。
如果你只想使用Foo<int>
,那么你可以在Foo.cpp
定義構造函數和析構Foo.cpp
,
template<typename T>
Foo<T>::Foo(){...} // or = default
和
template<typename T>
Foo<T>::~Foo(){...}
並且由於您在Foo.cpp
顯式實例化模板,鏈接器將找到該定義。 否則,您需要在頭文件中提供定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.