开发者

C++ Template specialisation issue

开发者 https://www.devze.com 2022-12-15 19:03 出处:网络
I have code that boils down to this: //Just a templated array class .. implementation does开发者_JS百科n\'t matter

I have code that boils down to this:

//Just a templated array class .. implementation does开发者_JS百科n't matter
template<int N>
struct Array {};

//A simple Traits like class
template<typename T>
struct MyTraits {}

//Specialization of the traits class
template<int N>
struct Foo< Array<N> >
{
  static void monkey() {};
}

int main()
{
  Foo< Array<3> >::monkey();
}

Unfortunately the compiler doesn't like it...

test.cpp: In function ‘int main()’:
test.cpp|17| error: ‘monkey’ is not a member of ‘Foo<Array<3> >’

What am I doing wrong, and how do I fix it? Thanks


The following works for me:

//Just a templated array class .. implementation doesn't matter
template<int N>
struct Array {};

//A simple Traits like class
template<typename T>
struct MyTraits {};

//Specialization of the traits class
template<int N>
struct MyTraits< Array<N> >
{
    static void monkey() {};
};

int main()
{
    MyTraits< Array<3> >::monkey();
}

The way you have Foo is incorrect, as you can see I changed it to match the comment. Additionally, you had a missing semicolon after the declaration of Foo/MyTraits. Lastly, for an array class I would recommend you use size_t as the type of N.


If you're interested the problem was this:

template<unsigned int N>
class V {};

template<typename T>
struct MyTraits
{
};

template< int N>
struct MyTraits< V<N> >
{
  static void monkey();
};

int main()
{
  MyTraits< V<4> >::monkey( );
}

Generates this error

error: ‘monkey’ is not a member of ‘MyTraits<V<4u> >’

This caused by a mismatch between the template type being an unsigned int in one spot and an int in another. (Kind of ugly)

Changing the traits specialization to be

template< unsigned int N>
struct MyTraits< V<N> >
{
  static void monkey();
};

makes everything work. (This issue was obscured as the definition of V is in 3rd party code).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号