我的一位同事告訴我他用他的團隊設計的一小塊設計讓我大開眼界。這是一種性狀類,他們可以專門在一個非常分離的方式。未定義的模板方法技巧?
我很難理解它是如何工作的,我仍然不確定我的想法,所以我想我會在這裏尋求幫助。
我們在這裏討論g ++,特別是3.4.2和4.3.2版本(它們似乎適用於兩者)。
的想法是很簡單:
1-定義接口
// interface.h
template <class T>
struct Interface
{
void foo(); // the method is not implemented, it could not work if it was
};
//
// I do not think it is necessary
// but they prefer free-standing methods with templates
// because of the automatic argument deduction
//
template <class T>
void foo(Interface<T>& interface) { interface.foo(); }
2-定義一個類,並且在源文件中專門接口這個類(定義它的方法)
// special.h
class Special {};
// special.cpp
#include "interface.h"
#include "special.h"
//
// Note that this specialization is not visible outside of this translation unit
//
template <>
struct Interface<Special>
{
void foo() { std::cout << "Special" << std::endl; }
};
3到使用,它的簡單太:
// main.cpp
#include "interface.h"
class Special; // yes, it only costs a forward declaration
// which helps much in term of dependencies
int main(int argc, char* argv[])
{
Interface<Special> special;
foo(special);
return 0;
};
如果沒有翻譯單元爲Special
定義Interface
的專用化符號,這是一個未定義的符號。
現在,我會認爲這將需要export
關鍵字,據我所知,這在我的知識中從未在g ++中實現(並且只在C++編譯器中實現過一次,其作者建議任何人不要在給定時間和精力的情況下它花了他們)。
我懷疑它有事情做與連接解決方法的模板...
- 你有沒有見過這樣的事之前?
- 它符合標準嗎?或者您認爲這是巧合嗎?
我必須承認,我對構建挺納悶......
因此,如果我理解正確的話,在「special.h」中包含「interface.h」並轉發聲明模板專用化'template <> struct Interface;'然後在「main.cpp」 「special.h」,以便使程序格式良好,即使'Interface :: foo'方法的定義永遠不會出現? –
2010-05-09 14:30:27
@Matthieu,正好!這就是你可以如何解決不幸的問題 – 2010-05-09 14:35:05
如果我正確地讀了這個,這意味着任何程序(多個翻譯單元),其中對於給定的一組參數存在模板的顯式專門化,但是在一些其他翻譯單元中,隱式專門化用於同一組參數是ODR違規,編譯器不需要 - 也可能不能 - 發佈診斷? 這是非常可怕的,也是另一個很好的理由,即在可能的情況下始終將主要模板部分專業化。 – Stewart 2010-05-09 18:24:27