Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template specialization by another template (of same class)

I'm writing an array class. This array class can contain again arrays as members. When implementing a printing function, I need specializations.

26:template <class T> class array : public vector<T>{
public:
    ...
       string* printToString();
    ...
};
...           
template <class T> string* array<T>::printToString(){
   ...  // generic function
}
template <> inline string* array<double>::printToString(){
   ...  // spezialization for double, works
}
561:template <class U> string* array<array<U>*>::printToString(){
   ...  // does not work
}

The last definition produces

src/core/array.h:561: error: invalid use of incomplete type ‘class array<array<T> >’
src/core/array.h:26: error: declaration of ‘class array<array<T> >’

The g++ version is g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3 if that matters. Any ideas what's the problem?

Thanks in advance, Thomas

like image 218
Thomas Handorf Avatar asked Sep 01 '11 10:09

Thomas Handorf


People also ask

What is explicit template specialization?

Explicit (full) specializationAllows customizing the template code for a given set of template arguments.

What is the use of template specialization?

This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming. Generic programming is an approach where generic data types are used as parameters in algorithms so that they work for variety of suitable data types.

What does template <> mean in C++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

What is the syntax for explicit class specialization?

What is the syntax to use explicit class specialization? Explanation: The class specialization is creation of explicit specialization of a generic class. We have to use template<> constructor for this to work. It works in the same way as with explicit function specialization.


Video Answer


1 Answers

As an alternative to David's solution, you can unconditionally forward the call to a set of overloaded functions:

template <class T> class array;
namespace details {
  template <class T> std::string array_print(array<T> const&);
  std::string array_print(array<double> const&); // Regular function 
  template <class T> std::string array_print(array<array<T> > const&);
}

template <class T> class array : private vector<T> {
public:
    ...
       std::string printToString() { return details::array_print(*this); }
    ...
};

namespace details { /* implementions after class is defined */ }
like image 147
MSalters Avatar answered Sep 27 '22 20:09

MSalters