Tom*_*ock 4 c++ templates static-members template-specialization
我正在尝试以下内容:
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();
Run Code Online (Sandbox Code Playgroud)
我把它包含在2个文件中 - a.cpp和b.cpp.我尝试编译并得到:
error C2998: 'const MyType *Test<void>::sm_object' : cannot be a template definition
Run Code Online (Sandbox Code Playgroud)
我认为我的C++语法很糟糕,但我无法想象我做错了什么.
我无法template<>
从变量定义中删除,因为我需要在多个翻译单元中,这会导致链接错误.
我可以将字段放入基类并使用CRTP为每个类型创建一个新实例,然后专门化不会妨碍,但为什么这个"直接"字段初始化不起作用?我一定错过了一些语法.
我正在使用VS2003 :(
从g ++来看,我认为您需要template<>
从该行中删除并将余数放在一个源文件中(而不是在标题中).由于它是一种特殊化,它就像一个普通的非模板静态,你没有在标题中定义.
在一些.C
文件中:
const MyType * const Test<void>::sm_object = new MyType();