Click to See Complete Forum and Search --> : About STL template class Vector


ok21
April 25th, 2005, 12:07 PM
Does anybody know how to write template class Vector with templated parameter:

#include <vector>
#include <iostream>

using namespace std ;

template <typename T>
class X
{
T val;
};

int main(int argc, char* argv[])
{

vector<X> Array; // Microsoft Dev. Studio 6 and .Net also write error in this line:
// error C2955: 'X' : use of class template requires template
// argument list
X<int> x; Array.push_back(x);
X<unsigned char> y; Array.push_back(y);
return 0;
}

MrViggy
April 25th, 2005, 12:16 PM
Well, yes. The line:
vector<X> Array;
is in error. When you declare a variable of a template type, you must provide the concrete type for the template.
#include <vector>
#include <iostream>

using namespace std ;

template <typename T>
class X
{
T val;
};

int main(int argc, char* argv[])
{
vector<X<int> > Array;
X<int> x;
Array.push_back(x);
/* The following will cause a compile error, however.
This is because the Array is a vector of X<int> not X<unsigned char>*/
//X<unsigned char> y;
//Array.push_back(y);
return 0;
}
If you want to store more then one kind of X item in the array, you'll need to change the way X is defined, however. Perhaps some kind of base class, and storing pointers to instances of X's?
Viggy

marten_range
April 25th, 2005, 12:20 PM
That will not work as std::vector only works with classes or instansiated template-classes.

So this works:

std::vector< X<int > > l_vector;



If you want to be able to push instances of arbitary and unrelated types on a vector in a type-safe manner have a look at.

1. boost::any (http://www.boost.org/doc/html/any.html)
2. boost::variant (http://www.boost.org/doc/html/variant.html)

boost::any requires less from the compiler in terms of standard compliance and is quicker to compile. boost::variant offer less runtime overhead and increased type-safety.

Hope this helps

ok21
April 25th, 2005, 01:44 PM
Solution with
vector<X<int> > Array;

is right and clear. But my goal is to create array and save it different types of variables and structures, like as CObject in MFC. For that I don't want use MFC, only STL for portability.

MrViggy
April 25th, 2005, 04:54 PM
Then you'll need to either store pointers to some base class (that's exactly what CObject is, a base class for all MFC objects), or you'll have to use the Boost libraries that marten_range suggested.

Viggy