其他分享
首页 > 其他分享> > c pimpl习惯用法:取决于模板参数的实现

c pimpl习惯用法:取决于模板参数的实现

作者:互联网

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

如果我尝试对结构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;
};

但如果可能,我想避免

解决方法:

该语言不允许您尝试执行的操作.

§14.7.3.16(FCD 2010-03-26)指出:

In an explicit specialization
declaration for a member of a class
template or a member template that
appears in namespace scope, the member
template and some of its enclosing
class templates may remain
unspecialized, except that the
declaration shall not explicitly
specialize a class member template if
its enclosing class templates are not
explicitly specialized as well. In
such explicit specialization
declaration, the keyword template
followed by a template-parameter-list
shall be provided instead of the
template<> preceding the explicit
specialization declaration of the
member. The types of the
template-parameters in the
template-parameter-list shall be the
same as those specified in the primary
template definition.

[ 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 ]

标签:pimpl-idiom,partial-specialization,c,templates,metaprogramming
来源: https://codeday.me/bug/20191010/1883501.html