簡體   English   中英

為什么編譯器實例化模板而我要求他不要?

[英]Why does the compiler instantiate templates while I ask him not to?

我想防止編譯器使用extern template隱式實例化某些模板。

以下片段按預期工作( static_assert不會觸發):

template<typename T>
void f() {
    static_assert(sizeof(T) == 0, "f()");
};

extern template void f<int>();

void g() {
    f<int>();
}

但是有了這個,編譯器似乎試圖實例化模板 function,因為static_assert確實觸發了:

struct S {
    template<typename T>
    void f() {
        static_assert(sizeof(T) == 0, "S::f()");
    } 
};

extern template void S::f<int>();

void g() {
    S s;
    s.f<int>();
}

有了這個, static_assert也會觸發,而我希望它不會:

template<typename T>
struct S {
    S(){};
    static_assert(sizeof(T) == 0, "S");
};

extern template struct S<int>;

void g() {
    S<int> s;
}

在我的實際情況中,我想加快編譯時間,但我觀察到編譯有extern template... ,與這些模板相關的符號不會出現在.o文件中(用nm查看),但它們實際上是編譯的......(我通過使用 clang 的-ftime-tracetemplight++觀察顯着的編譯時間來檢查)。

為什么extern template似乎沒有按預期工作?

謝謝!

顯式實例化聲明不能抑制所有實例化:畢竟,必須知道類的成員才能使用該類型的 object,並且內聯函數必須知道它們的定義才能內聯。

This example is just both of those in quick succession: the class template can't “protect” the member function template, and that member function template is inline because it's defined in its class.

后一條規則有點武斷:由於 ODR 的原因,它曾經被認為是必要的,但現代理解是整個 class(模板)定義的“合並”就足夠了。 因此,C++20 刪除了模塊中的隱式inline ,它與鏈接規則交互不良。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM