Thomas Kowalski wrote:
Hi,
I would like to write a template class Polygon<VertexTypthere vertex
typ can be eigther a pointer or a value typ.
It has an attribute:
std::vector<VertexTypvertices;
And a methode:
VertexValueTyp& vertex(int i);
that dereferences vertices[i] internally in case VertexTyp is a pointer
type.
How can I achieve this? Are there any step-by-step guides online?
Thanks in advance,
Thomas Kowalski
You have not given any details about VertexTyp. We don't know if you
are dealing with a template parameter that has member functions or is
it just a POD. I'm going to assume a POD for now.
As far as the method is concerned, its actually an operator that you
will prefer dealing with ( operator[] ). Basicly, since Polygon is just
a container wrapping a std::vector, why not match the interface that
std::vector already provides?
Here is an example that uses the name Container instead of Polygon and
a simple int instead of VertexTyp. Lets face it, if you can't get a
templated container handling primitive integers and their pointers
working, how will u be able to get to work with a more complex type?
#include <iostream>
#include <ostream>
#include <vector>
template < typename T >
class Container
{
std::vector< T v;
public:
Container() : v() { }
Container(size_t sz) : v(sz) { }
~Container() { }
/* member functions */
size_t size() const { return v.size(); }
void push_back( const T& r_t ) { v.push_back(r_t); }
T& operator[]( const unsigned index ) { return v.at(index); }
};
int main()
{
const unsigned sz( 5 );
Container< int integers(sz); // a vector of 5 integers
Container< int* pointers; // an empty vector of pointers to int
for ( size_t i = 0; i < integers.size(); ++i )
{
integers[i] = static_cast<int>(i);
pointers.push_back( &integers[ i ] );
}
// test
*pointers[0] = 101;
for ( size_t i = 0; i < integers.size(); ++i )
{
std::cout << pointers[i] << "\t";
std::cout << integers[i] << std::endl;
}
return 0;
}
/*
0x503010 101
0x503014 1
0x503018 2
0x50301c 3
0x503020 4
*/
Remember that your VertexTyp needs to support copy semantics.