c++ pimpl idiom :根据模板参数实现
在 这个问题中,我没有成功地询问如何使用不同的 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;
};
但如果可能的话,我想避免它
In this question I unsuccessfully asked how to use different pimpl implementation depending on a template argument.
Maybe this example ilustrates better what I am trying to do :
#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;
}
It still fails if I try to specialize the struct C (the above doesn't compile)
So, is it possible to do?
I know a work around like this :
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;
};
but if possible, I would like to avoid it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你想要做的事情是语言不允许的。
§ 14.7.3.16 (FCD 2010-03-26) 规定:
What you're trying to do is not allowed by the language.
§ 14.7.3.16 (FCD 2010-03-26) states: