2016-05-30 34 views
1
#include <iostream> 

template <typename T1, typename T2> 
class B{ 
public: 
    void update(){ std::cerr<<__PRETTY_FUNCTION__<<std::endl; } 
    void func1(){ std::cerr<<__PRETTY_FUNCTION__<<std::endl; } 
    void func2(){ std::cerr<<__PRETTY_FUNCTION__<<std::endl; } 
}; 

template <typename T1> 
class B<T1, int>{ 
public: 
    void update(){ std::cerr<<__PRETTY_FUNCTION__<<"(specialization)"<<std::endl;} 
}; 

int main(){ 
    B<int, double> b1; 
    b1.update(); 
    b1.func1(); 
    B<int, int> b2; 
    b2.update(); 
    //b2.func1();//there's no function 'func1' in B<int,int> 
} 

我想專門針對特定模板參數(數據類型)的update函數。特定成員函數的部分專業化

所以我試圖專注於template class B,但似乎我必須再次實現整個成員函數。

因爲其他成員之間的專業化完全相同,重新實現整個成員看起來很麻煩。

這種情況有什麼解決方法嗎?

+0

[C++模板部分特例成員函數(的可能的複製http://stackoverflow.com/questions/15374841/c-template - 部分專業化 - 成員函數) – LogicStuff

回答

2

標記分派調用update

template <typename> struct tag {}; 

template <typename T1, typename T2> 
class B 
{ 
public: 
    void update() 
    { 
     return update(tag<B>()); 
    } 

private: 
    template <typename U1> 
    void update(tag<B<U1, int> >) 
    { 
     // specialization 
    } 

    template <typename U1, typename U2> 
    void update(tag<B<U1, U2> >) 
    { 
     // normal 
    } 
}; 

DEMO

+0

哇。這是一個神奇!謝謝。 –