0

this question我失敗問到如何使用不同的PIMPL實現依賴於一個模板參數實現。C++ PIMPL方法:根據模板參數

也許這個例子ilustrates好什麼,我試圖做的:

#include <iostream> 

template< int N, typename T > 
struct B 
{ 
    B() : c(new C<N>) 
    {} 

    template< int M > 
    struct C; 
    C<N> *c; 
}; 

template< int N, typename T > 
template< int M > 
struct B< N, T >::C 
{ 
    int a[M]; 
}; 

// version 1 that doesn't work  
    template< int N, typename T > 
    template< > 
    struct B< N, T >::C<0> 
    { 
     int a; 
    }; 
// version 2 that doesn't work 
    template< typename T > 
    template< int M > 
    struct B< 0, T >::C 
    { 
     int a; 
    }; 


int main() 
{ 
    B< 0, float > b0; 
    B< 1, int >  b1; 

    std::cout << "b0 = " << sizeof(b0.c->a) << std::endl; 
    std::cout << "b1 = " << sizeof(b1.c->a) << std::endl; 
} 

,如果我嘗試專門的結構C(上面沒有編譯)

所以還是失敗,它是可能做什麼?

我知道周圍的工作是這樣的:

template< int M > 
struct D 
{ 
    int a[M]; 
}; 
template< > 
struct D<0> 
{ 
    int a; 
}; 

template< int N, typename T > 
template< int M > 
struct B< N, T >::C 
{ 
    D<M> helper; 
}; 

,但如果可能的話,我想,以避免它

+0

是否'乙中:C 的真正定義'使用'N'和/或'T'呢?如果不是,爲什麼要在類模板'B'的一員? – aschepler 2011-03-24 20:46:24

+0

@aschepler是,它使用了,但這個例子只是簡化了什麼FCD代表問題 – 2011-03-24 21:16:16

回答

3

你試圖做的是不是由語言允許的。

§14.7.3.16(FCD 2010-03-26)規定:

在一個顯式特 聲明一類 模板的成員或成員模板 出現在命名空間範圍,所述成員 模板和它的一些封閉 類模板可以保持 非特,除了 聲明不得明確 專業類成員模板,如果 它的外圍類模板並未 也明確專門化。在 這種顯式專業化 聲明,隨後模板參數列表 的關鍵字模板 應提供代替 模板<>的 構件的明確 專業化聲明之前。類型在 模板參數列表的 模板參數的應是 相同在初級 模板定義中指定。

[ Example: 
template <class T1> class A { 
    template<class T2> class B { 
     template<class T3> void mf1(T3); 
     void mf2(); 
    }; 
}; 
template <> template <class X> 

class A<int>::B { 
    template <class T> void mf1(T); 
}; 
template <> template <> template<class T> 
void A<int>::B<double>::mf1(T t) { } 
template <class Y> template <> 
void A<Y>::B<double>::mf2() { } // ill-formed; B<double> is specialized but 
// its enclosing class template A is not 
—end example ] 
+0

? – 2011-03-25 08:37:34

+0

的方式,即§在當前的C++標準14.7.3.18,和那款回答我的問題。由於 – 2011-03-25 08:40:01

+0

FCD - 最終委員會草案。 – 2011-03-28 17:37:01