【发布时间】:2014-02-28 06:53:45
【问题描述】:
我遇到的问题与此处讨论的主题非常相似: How to properly specialize a templatized static const member that is the same type as its parent
这是我的代码:
template <class T>
class p3d
{
public:
p3d() {
x = 0;
}
p3d(const T &_x) {
x = _x;
}
static const p3d<T> origin;
T x;
};
typedef p3d<float> p3df;
int main(int, char**)
{
p3df p = p3df::origin;
return 0;
}
// elsewhere in a *.cpp file
template<> const p3df p3df::origin(0.0f);
在 Clang 等严格的编译器下编译时,出现以下错误:
explicit specialization of 'origin' after instantiation
template<> const p3df p3df::origin(0.0f); -> implicit instantiation first required here
解决办法是移动
template<> const p3df p3df::origin(0.0f);
在 typedef 之前。这个解决方案的问题在于它会导致多重定义的符号,因为现在p3df::origin 在每个使用矢量头的文件中都定义了。有什么方法可以正确专门化静态 const typedef-ed 模板,同时避免使用 typedef 在所有源文件中重复定义?
【问题讨论】:
标签: c++ templates template-specialization