2009-12-29 57 views
1

我正在處理一些生成的具有破損多態性的類。對於每個生成的類T,都有一些T_type_info,T_writer,T_reader類,這些類僅在概念上與T有關。模板返回類型/演示爲模板的功能

我想要做的是這樣的:

template <class T> class Wrapper 
{ 
public: 
    template <class W> W topic_cast(BrokenBaseClassWriter* p); 
    // other operations with the same problem ... 
}; 

template <> class Wrapper<MyTopic> 
{ 
public: 
    template <> MyTopicWriter* topic_cast(BrokenBaseClassWriter* p) { ... } 
}; 

所以,我可以做這樣的事情:

void Write(const Wrapper<T>& topic) 
{ 
    BrokenBaseClassWriter p = not_important; 
    topic.topic_cast(p)->do_stuff(); 
} 

我的T類是從IDL生成是概念存在於應用程序空間。它們不是來自任何東西。在我上面的例子中,W並不是一個獨立的參數,它是「不依賴於T的東西」。我試圖在應用程序中保留T的所有知識,並在後端保留T'的所有知識(不知道T)。

然而,編譯器說我的topic_cast函數不是模板函數 - 我想是因爲模板出現在返回類型中,並且它不會與任何其他實例區分開來。我知道(模板只有返回類型不同)是不合法的。只有在我的情況下,它確實是獨一無二的,因爲W不是一個獨立的參數。但與編譯器爭論很少有幫助。

我可以這樣做,還是有另一種方法來做到這一點「鑄造爲模板類型的功能」?

回答

1

難道這不是用特質系統實現的嗎?

template <typename T> struct my_traits 
{ 
}; 

template <> struct my_traits<MyClass> 
{ 
    typedef MyWriter writer_type; 
}; 

template <typename T> struct Wrapper 
{ 
    typename my_traits<T>::writer_type topic_cast(); 
}; 
+0

這就是我正試圖用我上面建造的方形輪到達。封裝不再需要 - 類型映射是其最初的目的。謝謝 – swarfrat

0

這可不行:

topic.topic_cast(p)->do_stuff(); 

因爲編譯器無法推斷返回類型。
所以,你必須明確地告訴你想要什麼返回類型,編譯器:

topic.topic_cast<MyType>(p)->do_stuff(); 

您提供的實現是一個特定的類型。
所以,當你使用特定類型的代碼將被製作:

0

這個用gcc編譯:

class BrokenBaseClassWriter; 
class MyTopic; 
class MyTopicWriter; 

template <class T> class Wrapper 
{ 
public: 
    template <class W> W *topic_cast(BrokenBaseClassWriter* p); 
    // other operations with the same problem ... 
}; 




template <> template<> 
MyTopicWriter *Wrapper<MyTopic>::topic_cast<MyTopicWriter>(BrokenBaseClassWriter* p) 
{ 
    return 0; 
} 


int main(int argc, int argv) 
{ 
    BrokenBaseClassWriter* p = NULL; 
    Wrapper<MyTopic> caster; 
    MyTopicWriter *casted = caster.topic_cast<MyTopicWriter>(p); 
} 

當然,它仍然暴露在MyTopicWriter你的主代碼...