簡體   English   中英

C ++模板顯式實例化

[英]C++ template explicit instantiation

我有這樣的工作代碼。

#include <iostream>

struct A{
   template<typename T>
   void foo(T val);
};

template<typename T> void A::foo(T val)
{
  std::cout << val << std::endl;
}

// link template "against" int
template void  A::foo(int val);

// #include header here

int main(){
    A a;
    a.foo(12);
}

模板位於單獨的CPP文件中,但是由於顯式實例化,所以鏈接有效:

template void  A::foo(int val);

然后,我做了一些重構,代碼看起來像這樣:

#include <iostream>

template<typename G>
struct A{
   template<typename T>
   void foo(T val);
};

template<typename G>
template<typename T> void A<G>::foo(T val)
{
  std::cout << val << std::endl;
}

// link template "against" int - not working
//template<typename G>
//template void A<G>::foo(int val);

int main(){
    A<float> a;
    a.foo(12);
}

如何“鏈接” T = int,但保持G“未知”?

這稱為顯式實例化。

您無法執行此操作,因為G是未知的,並且它不是單個類型。 它是一組類型。

你不可以做這個。 為了從模板實際生成代碼(我想這就是您所說的link ),編譯器需要知道所有模板參數。

因此,您剩下了模板實例化的標准選項:要么明確告訴編譯器將使用TG ,要么讓編譯器無論在哪里使用都可以看到模板成員的完整代碼(即,在標頭中包含代碼) 。

TL; DR,你做不到

在您的情況下,我只指定您打算使用的類型

template void A<float>::foo(int val);

或(相當笨重)顯式實例化G可以用於的所有類型。

如果無法推導G則無法顯式實例化模板。

請注意,鏈接起作用不是因為此語法是鏈接器命令,而是因為您的編譯器正在生成稍后在鏈接時找到的代碼。 在這里查看更多

暫無
暫無

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

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