【发布时间】:2012-11-21 11:09:30
【问题描述】:
我正在尝试为数学编程编写一个大小和类型的通用向量类。我在部分专业化方面遇到问题。
当我尝试将向量类的成员方法专门化为给定大小时,就会出现问题。
我可以举一个简单的例子:
template <size_t Size, typename Type>
class TestVector
{
public:
inline TestVector (){}
TestVector cross (TestVector const& other) const;
};
template < typename Type >
inline TestVector< 3, Type > TestVector< 3, Type >::cross (TestVector< 3, Type > const& other) const
{
return TestVector< 3, Type >();
}
void test ()
{
TestVector< 3, double > vec0;
TestVector< 3, double > vec1;
vec0.cross(vec1);
}
在尝试编译这个简单示例时,我收到一个编译错误,指出“交叉”特化与现有声明不匹配:
error C2244: 'TestVector<Size,Type>::cross' : unable to match function definition to an existing declaration
see declaration of 'TestVector<Size,Type>::cross'
definition
'TestVector<3,Type> TestVector<3,Type>::cross(const TestVector<3,Type> &) const'
existing declarations
'TestVector<Size,Type> TestVector<Size,Type>::cross(const TestVector<Size,Type> &) const'
我尝试将 cross 声明为模板:
template <size_t Size, typename Type>
class TestVector
{
public:
inline TestVector (){}
template < class OtherVec >
TestVector cross (OtherVec const& other) const;
};
template < typename Type >
TestVector< 3, Type > TestVector< 3, Type >::cross< TestVector< 3, Type > > (TestVector< 3, Type > const& other) const
{
return TestVector< 3, Type >();
}
此版本通过编译但在链接时失败:
unresolved external symbol "public: class TestVector<3,double> __thiscall TestVector<3,double>::cross<class TestVector<3,double> >(class TestVector<3,double> const &)const
我在这里缺少什么? 谢谢, 弗洛伦特
【问题讨论】:
-
一个问题是你没有部分特化
class,而是其中的一些功能,你的class这里是模板化,所以是部分特化应该是另一个类模板。 -
@TonyTheLion 谢谢,所以你说我应该专门研究完整的 Vector 类?我的问题是它需要我重写整个类(它包含很多方法,而不仅仅是交叉)
-
已提出问题。看到这个答案:stackoverflow.com/questions/13444615/…
标签: c++ templates specialization partial-specialization