Any generic type in a C ++ class

Is there a way in C ++ to specify any type * as the type of the template, for example, using a wildcard or some kind of keyword.

I remember in Java we can do this using? wildcard as a generic type, such as HashMap<Long, ?> .

I am trying to better explain the question using code example. Suppose we have the following notation class:

 template<typename T> class Record { private: T content; long size; public: Record(T _content, long _size) { this->content = _content; this->size = _size; } T getContent() { return this->content; } long getSize() { return this->size; } }; 

and suppose we want to use instances of the above class without specifying the exact type (I used "in the next class"), simply because it is useless if the Computer class uses only the Record::getSize() method:

 class Computer { public: long long computeTotalSize(vector<Record<?>> recordVector) { long long totalSize = 0; for (vector<Record<?>>::iterator it = recordVector.begin() ; it != recordVector.end(); ++it) totalSize += (*it).getSize(); return totalSize; } }; 
+6
source share
2 answers

You can make the computeTotalSize template function with the recording template parameter as the template parameter:

 template <typename T> long long computeTotalSize(vector<Record<T>> recordVector) { long long totalSize = 0; for (vector<Record<T>>::iterator it = recordVector.begin() ; it != recordVector.end(); ++it) totalSize += (*it).getSize(); return totalSize; } 

Note that you must also pass a vector by reference to avoid copying the entire object:

 long long computeTotalSize(const vector<Record<T>>& recordVector) 
+8
source

This cannot be done in the same way as in Java, because C ++ templates are fundamentally different from Java generics (C ++ templates generate completely different types, not fancy constructions on top of a type erased by type). However, you can make a computeTotalSize function template:

 class Computer { public: template <class T> long long computeTotalSize(const vector<Record<T>>& recordVector) { long long totalSize = 0; for (auto it = recordVector.begin() ; it != recordVector.end(); ++it) totalSize += it->getSize(); return totalSize; } }; 

Please note: I allowed to simplify the syntax of the code a bit; the only change in behavior is to use const& to pass the vector to prevent it from being copied.

Note that changing const& requires getSize() be marked as a function of the const member:

 long getSize() const { return size; } 

Since for a function called getSize() it would be very unexpected to change the object that he called, this is actually good.

+7
source

All Articles