簡體   English   中英

模板部分特化問題

[英]Template partial specialization problems

我正在嘗試為數學編程編寫一個大小和類型泛型向量類。 我遇到部分專業化的問題。

當我嘗試將給定大小的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 > 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

我在這里錯過了什么? 謝謝,弗洛朗

一種方法是將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, T>& a, const Vec<3, T>& b) {
    // specialize definition
  }
};

您不能部分專門化方法。 你可以在某些條件下超載。 在這里,你可以對你的班級進行部分專業化

template <size_t Size, typename Type> class TestVector
{
public:
    inline TestVector (){}
    TestVector cross (TestVector const& other) const;
};

定義一般行為:

TestVector<size_t Size, typename Type>::cross (TestVector const& other) const {
     // general
}

和一個專門的模板,使您能夠為案例int定義特定的行為是3

template <typename Type> class TestVector<3, Type>
{
public:
    inline TestVector (){}
    TestVector cross (TestVector const& other) const;
};

與自定義行為的定義:

TestVector<typename Type>::cross (TestVector const& other) const {
     // custom
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM