[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

How to declare vector of generic template class

mzdude

11/25/2008 9:31:00 PM

I'm trying to upgrade an existing design. It currently looks like
struct Foo {
double x; // can be raw or rate
};
One is never quite sure what x contains. I would like to be more
explicit.

So I thought I would do the following

struct Raw {
Raw( double r, double scalar = 1.0 ) :
raw(r) { scalar; }
operator double () {return raw;}
private:
double raw;
};

struct Rate {
Rate( double r, double scalar ) :
rate( r / scalar ) {}
operator double() {return rate;}
private:
double rate;
};

template< class T>
struct Foo {
Foo(const T &x_) : x(x_) {}

T x;
bool operator==(const T &rhs); // details omitted
};

Now I can do things like
Foo<Raw> f1(Raw(500));
Foo<Rate> f2(Rate(500,.01));

What I would like to do is create a function that can return a vector
of either Raw or Rate objects. I know I can't overload a function
simply on return type.

int f();
float f(); // compile error

but I can do
template<typename T>
T f() {}

int x1 = f<int>();
float x2 = f<float>();

Right now what I have is

#define FooVector(T) std::vector<Foo<T> >

template<typename T>
FooVector(T) BuildList()
{
FooVector(T) v;
v.push_back(T(5,0.1));
return v;
}

but I want to get rid of the macro.

Right now I'm struggling with the syntax of declaring a vector of
Foo objects.

What I want to do is
// the following gives a compile error
typedef template<typename T> std::vector<Foo<T> > FooVector<T>;

and ultimately

template<typename T>
FooVector<T> BuildList();

Is it possible? What is the correct syntax?


Thanks.
1 Answer

Andrey Tarasevich

11/25/2008 9:42:00 PM

0

mzdude wrote:
>
> Right now what I have is
>
> #define FooVector(T) std::vector<Foo<T> >
>
> template<typename T>
> FooVector(T) BuildList()
> {
> FooVector(T) v;
> v.push_back(T(5,0.1));
> return v;
> }
>
> but I want to get rid of the macro.
>
> Right now I'm struggling with the syntax of declaring a vector of
> Foo objects.
>
> What I want to do is
> // the following gives a compile error
> typedef template<typename T> std::vector<Foo<T> > FooVector<T>;
>
> and ultimately
>
> template<typename T>
> FooVector<T> BuildList();
>
> Is it possible? What is the correct syntax?
>

What you need is a "parametrized typedef" (a "template typedef").
Currently there's no such feature in C++, but in many cases you can
simulate it with a macro (which is exactly what you did already), or
better by using a wrapper template

template <typename T> struct FooVector {
typedef std::vector<Foo<T> > type;
};

Usage

template<typename T> FooVector<T>::type BuildList();

That's is a bit inelegant, but that's all we have at this time.

--
Best regards,
Andrey Tarasevich