2010-01-27 83 views
2

我有一個模板類,裏面有一個模板方法,給出兩個模板參數T和U.該操作相當昂貴,並且在分析中顯示爲主要用途的CPU時間。我可以在某種程度上對其進行優化,但僅適用於T == U(這很常見)的情況,但我不確定這樣做的語法...當模板參數相同時,C++優化類模板功能

問題中的類和方法看起來像這樣的:

template<typename T>class Foo 
{ 
public: 
    ... 
    template<typename U>U bar()const; 
}; 

富::酒吧一般是從一些其他的模板代碼調用,所以即使我創建了一個單獨的方法(如「T fastBar()const的」)我不知道怎麼的id去製作其他模板代碼在可能的情況下調用該版本...

我試圖爲T == U創建明確的特化,但VC9給了我錯誤

template<typename T>template<>T Foo<T>::bar<T>()const 

錯誤C2768:「富::酒吧」:非法使用顯式模板參數

回答

4

因此,有關於模板類的模板成員明確分工一些奇怪的事情。看到這個question

一個解決方法是使用一個輔助類

template< typename T, typename U> 
struct FooDispatchHelper 
{ 
    static U dispatch(const Foo<T> * f) 
    { 
    return f->template bar_internal<U>(); 
    } 
}; 

template< typename T > 
struct FooDispatchHelper<T,T> 
{ 
    static T dispatch(const Foo<T> * f) 
    { 
    return f->bar_fast(); 
    } 
}; 

template<typename T>class Foo 
{ 
public: 
... 
    template<typename U>U bar() const 
    { 
     return FooDispatchHelper<T,U>::dispatch(this); 
    } 

    template<typename U> U bar_internal() const; 
    T bar_fast() const; 

}; 

更完整的examnple可以發現here

+0

+1:嘿,我的編譯,但沒有鏈接:> – 2010-01-27 23:20:27

+0

它不那麼怪異:你不能專注於成員f沒有明確地專門化它們的封閉模板類,並且你不能部分地專門化函數 - 因此下一個最好的通用解決方案是將調用轉發給部分專用類的成員函數。 – 2010-01-28 00:40:13

2

一種可能性是使用boost::enable_if/disable_if選擇哪一個版本將可用於特定實例:

#include <iostream> 
#include <boost/utility/enable_if.hpp> 
#include <boost/type_traits.hpp> 

template <class T> 
class Foo 
{ 
public: 
    template <class U> 
    typename boost::disable_if<boost::is_same<T, U>, U>::type bar() const 
    { std::cout << "Different U\n"; return U(); } 

    template <class U> 
    typename boost::enable_if<boost::is_same<T, U>, U>::type bar() const 
    { std::cout << "Same U\n"; return U(); } 
}; 


int main() 
{ 
    Foo<int> f; 
    f.bar<int>(); 
    f.bar<float>(); 
}