c++ - Nontype template class member specialization -
consider following c++ code:
template <int k> struct kdata { float data[k]; }; template<int k> class kclass { public: typedef kdata<k> data; data m_data; data square() { data result; for(int = 0; < k; ++i) result.data[i] = m_data.data[i] * m_data.data[i]; return result; } // specialization k = 2 template<> kclass<2>::data square(); }; template<> kclass<2>::data kclass<2>::square() { data result; result.data[0] = m_data.data[0] * m_data.data[0]; result.data[1] = m_data.data[1] * m_data.data[1]; return result; } int main() { kclass<2> c; c.m_data.data[0] = c.m_data.data[1] = 1.f; c.square(); return 0; }
it has 'kcalss' has template data member ('m_data') , method performs computations on data member ('square()'). want make specialization of 'square()' case when k = 2, example.
trying compile 4.6.7 or 4.7.2 gives following error:
main.cpp:23:14: error: explicit specialization in non-namespace scope 'class kclass'
main.cpp:24:5: error: 'data' in 'class kclass<2>' not name type
any idea of i'm doing wrong?
thanks in advance.
=== edit ===
a workaround found declare second 'square()' method template well:
template<int k2> typename kclass<k2>::data square();
it works nicely, allows user call 'aquare()' passing template parameter different class, e.g:
kclass<2> c; c.square<3>;
which gives "undefined reference to" linking error.
=== edit (solution) ===
all right, solution simpler expected. had remove template declaration:
template<> inline kclass<2>::data square();
, unnecessary.
template<> kclass<2>::data kclass<2>::square() ^^^^^^^^ {
and have remove this. not how specialize member function. member function can not specialized in class scope. needs specialized within surrounding namespace of class declaration.
template<> kclass<2>::data square();
Comments
Post a Comment