c ++ pimpl idiom:实现取决于模板参数

时间:2011-03-24 20:24:33

标签: c++ templates metaprogramming partial-specialization pimpl-idiom

this question中,我未能成功地询问如何根据模板参数使用不同的pimpl实现。

也许这个例子更能说明我想做的事情:

#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;
}

如果我尝试专门化struct 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;
};

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

1 个答案:

答案 0 :(得分:3)

语言不允许您尝试做的事情。

§14.7.3.16(FCD 2010-03-26)声明:

  

明确的专业化   一个班级成员的声明   模板或成员模板   出现在命名空间作用域中的成员   模板和它的一些封闭   类模板可能会保留   非专业,除了   声明不得明确   如果要专门化一个类成员模板   它的封闭类模板不是   也明确专业化。在   这种明确的专业化   声明,关键字模板   后跟一个template-parameter-list   应提供而不是   模板&LT;&GT;在显式之前   专业化宣言   会员。的类型   模板参数   template-parameter-list应该是   与主要指定的相同   模板定义。

[ 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 ]
相关问题