gpt4 book ai didi

C++ pimpl idiom : Implementation depending on a template parameter 收藏

转载 作者:行者123 更新时间:2023-11-28 01:07:29 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于C++ pimpl idiom : Implementation depending on a template parameter 收藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5425065/

25 4 0