c – 模板部分特化问题
发布时间:2020-12-16 07:02:19 所属栏目:百科 来源:网络整理
导读:我正在尝试为数学编程编写一个大小和类型泛型向量类.我遇到部分专业化的问题. 当我尝试将给定大小的vector类的成员方法专门化时,会出现问题. 我可以提供一个简单的例子: template size_t Size,typename Typeclass TestVector{public: inline TestVector (){
我正在尝试为数学编程编写一个大小和类型泛型向量类.我遇到部分专业化的问题.
当我尝试将给定大小的vector类的成员方法专门化时,会出现问题. 我可以提供一个简单的例子: 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); } 在尝试编译这个简单示例时,我收到一个编译错误,指出’cross’特化与现有声明不匹配: 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 >::cross< TestVector< 3,Type > > (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 我在这里错过了什么? 解决方法
一种方法是将cross定义为“functor”(即带有operator()的类).
template<size_t S,typename T> class Vec { // ... stuff friend struct Cross<S,T>; Vec<S,T> cross(const Vec<S,T>& other) { return Cross<S,T>()(*this,other); } // ... more stuff }; template<size_t S,typename T> struct Cross { Vec<S,T> operator() (const Vec<S,T>& a,const Vec<S,T>& b) { // general definition } }; // Partial specialization template<typename T> struct Cross<3,T> { vec<3,T> operator() (const Vec<3,const Vec<3,T>& b) { // specialize definition } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |