静态字段初始化的模板部分特化
我正在尝试类似以下内容:
struct MyType { };
template <typename T>
struct Test
{
static const MyType * const sm_object;
};
template <>
struct Test<void>
{
static const MyType * const sm_object;
};
template <typename T> const MyType * const Test<T>::sm_object = new MyType();
template <> const MyType * const Test<void>::sm_object = new MyType();
我将其包含在 2 个文件中 - a.cpp 和 b.cpp。我尝试编译并得到:
error C2998: 'const MyType *Test<void>::sm_object' : cannot be a template definition
我认为我的 C++ 语法很糟糕,但我不认为我做错了什么。
我无法从变量定义中删除 template<>
,因为我在多个翻译单元中需要它,这会导致链接错误。
我可以将该字段放入基类中,并使用 CRTP 为每种类型创建一个新实例,然后专业化就不会妨碍,但为什么这种“直接”字段初始化不起作用?我一定缺少一些语法。
我正在使用 VS2003 :(
I'm attempting something like the following:
struct MyType { };
template <typename T>
struct Test
{
static const MyType * const sm_object;
};
template <>
struct Test<void>
{
static const MyType * const sm_object;
};
template <typename T> const MyType * const Test<T>::sm_object = new MyType();
template <> const MyType * const Test<void>::sm_object = new MyType();
I include this in 2 files - a.cpp and b.cpp. I attempt to compile and get:
error C2998: 'const MyType *Test<void>::sm_object' : cannot be a template definition
I assume my C++ syntax is bad, but I can't think what I'm doing wrong.
I can't remove the template<>
from the variable definition, as I need this in multiple translation units, and that would result in a link error.
I could put the field into a base class and use the CRTP to create a new instance per type, and then the specialization wouldn't get in the way, but why doesn't this 'direct' field initialisation work? I must be missing some piece of syntax.
I'm using VS2003 :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 g++ 来看,我认为您需要从该行中删除
template<>
并将其余部分放在一个源文件中(而不是在标头中)。因为它是一个专业化,所以它就像一个普通的非模板静态,您没有在标头中定义。在某些
.C
文件中:const MyType * const Test::sm_object = new MyType();
Judging from g++ I think you need to remove the
template<>
from that line and put the remainder in just one source file (not in the header). Since it's a specialization it's just like a normal non-template static which you don't define in a header.In some
.C
file:const MyType * const Test<void>::sm_object = new MyType();
我相信你想做这样的事情
I believe that you want to do something like this
我相信某些人可能会对以下代码感兴趣:
I believe the following code could be of quite some interest for some people: