![](/img/trans.png)
[英]Should a friend function of a class template become friend to all instantiations?
[英]Can all instantiations of a class template share the same template independent member function?
在下面的示例中,我假設將有兩個不同的類模板函數get_count()
實例化,這是多余的,因為它們不依賴於模板參數。 這是真的(或優化了嗎?),是否有一種方法可以使模板的所有實例化使用一個公共函數(可能是一些模板參數通配符,如<*>
?),當涉及到一些成員函數時?
template<class T>
class A {
private:
T obj;
int count;
public:
int get_count();
};
template<class T>
int A<T>::get_count() { // This function doesn't really need to
// depend on the template parameter.
return this->count;
}
int main() {
A<int> a; //<--First template instantiation
A<bool> b; //<--Second template instantiation
int i = a.get_count(); //<--Could theoretically use the same code
int j = b.get_count(); //<--
return 0;
}
另外,如果重新安排成員變量怎么辦?
您假設所有實例化都可以使用相同的代碼A<..>::get_count()
,這是完全錯誤的。
看班級成員:
T obj;
int count;
因此,tamplate-argument T
確定count
的偏移量,這是成員get_count()
返回的。
無論如何,如果兩個實例化恰好產生相同的指令,則不會禁止編譯器合並它們。
作為QoI問題,如果啟用了優化,則應該如此。
有一種方法可以讓多個類在不依賴編譯器優化的情況下對函數使用相同的代碼:
從提供該功能的共同基礎派生。
struct A_base {
int get_count();
protected:
int count;
}
template<class T>
class A : A_base {
T obj;
};
int A_base::get_count() {
return this->count;
}
(盡管如此,as-if-rule仍然是最重要的:編譯器可能會重復代碼以暴露優化可能性,否則無法使用。)
是的,有一種方法,它是一種使用的實現技術:
創建一個不依賴於模板參數的基類,並在其中放置與模板無關的代碼。 這將使實例化只進行一次。 對於模板參數相關代碼,請在模板類本身中執行:
class base {
int count;
public:
std::size_t get_count()...
};
template <class T>
class derived : public base {};
類似的技術用於減少實現中的代碼膨脹。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.