How to declare vector of generic template class

M

mzdude

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.
 
A

Andrey Tarasevich

mzdude said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top