Skip to main content
GameDev.net gamedev.net
🔒 Locked

Template Typ *

Started by schiggl Jun 3, 2002 at 10:45 AM 1 replies 700+ views
Original Post
schiggl
schiggl
I want to make a template class, that only accept Pointers like:
MyClass < int * >, MyClass < char * >, ...
  
and NOT:
MyClass < int > or MyClass < char > or ....
  
How can i do this? If i'm able to. [edited by - schiggl on June 4, 2002 5:07:22 AM]
Fruny
Fruny

  
template<typename T> class MyClass;
// No implementation for ''generic'' case


template<typename T> class MyClass<T*>
{
// Implementation for pointer case

};


Will not work with VC++ which does not support partial template specialisation.

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Fruny
Fruny
Actually, here''s using the ''usual'' VC++ workaround.
Get the Boost library for type_traits to get the ''is_pointer'' template (makes life easier).


  
#include <boost/type_traits.hpp>


struct MyClassPointer
// This struct holds the specialized implementation

// for pointer types.

// MyClassPointer has no template parameter because

// we would need partial template specialisation...

// and this is what we are trying to avoid.

// Instead, it has a templated inner class.

{
template<class T> class Implementation
{
public:
void Foo()
{
// do something

};
};
};

template<bool IsPtr> struct MyClassDispatch;
// No implementation of the general case


template<> struct MyClassDispatch<true>
// Redirect to MyClassPointer in the pointer case

{
typedef MyClassPointer Type;
};


template<class T> class MyClass
{
public:
inline void Foo()
{
typedef typename MyClassDispatch<boost::is_pointer<T>::value>::Type Type;
// select a specialisation implementation

Type::Implementation<T>::Foo();
// reapply the template parameter T and call the ''right'' Foo()

};
};


Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.