2011.04.08 - template overloading for array types

yesterday Mariusz, a friend from my current work, showed me a short article describing interesting feature of C++ – template overloading for array types. it's very nice thing, since you can easily tell smart pointer if argument it takes is a pointer to some object or array of objects (i.e. “new X” or “new X[10]”, that both are pointer to by “X*”). for example consider the following code:

#include <iostream>
 
using namespace std;
 
template<typename T>
struct Test
{
  static void f(void)
  {
    cout<<"Test<T>"<<endl;
  }
};
 
template<typename T>
struct Test<T[]>
{
  static void f(void)
  {
    cout<<"Test<T[]>"<<endl;
  }
};
 
int main(void)
{
  Test<int*>::f();
  Test<int[]>::f();
  return 0;
}

output on the screen is be:

Test<T>
Test<T[]>

another interesting fact is that it is actually used in C++0x standard library implementation of std::unique_ptr<>, to use “delete” for object pointers and “delete[]” for array-of-objects pointers.

blog/2011/04/08/1.txt · Last modified: 2013/05/17 19:08 (external edit)
Back to top
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0