Changing a non-template class to a template class easily

G

gg

Let us say I have the following class -

class X {
int y;
};

Lot of other classes start using X.

Now, I want to make X a template class so that I can write,

template<class T>
class X {
T y;
};

How to minimize the impact on the client?

One way I can think of is, define the template class with a default
argument and with a new name,

template<class T = int>
class X1 {
T y;
};

and then do a typedef,

typedef X1<> X;

So the older clients can continue using the name X and they will get
the desired behavior.

The newer clients can use X1<float> etc.

Is this a good approach and are there any better ones?

Thanx,
gg
 
V

Victor Bazarov

gg said:
Let us say I have the following class -

class X {
int y;
};

Lot of other classes start using X.

Now, I want to make X a template class so that I can write,

template<class T>
class X {
T y;
};

How to minimize the impact on the client?

One way I can think of is, define the template class with a default
argument and with a new name,

template<class T = int>
class X1 {
T y;
};

and then do a typedef,

typedef X1<> X;

There is no need for the default template argument. You could simply
say

typedef X1 said:
So the older clients can continue using the name X and they will get
the desired behavior.

The newer clients can use X1<float> etc.

Is this a good approach and are there any better ones?

Looks fine to me.

V
 
M

msalters

gg schreef:
Let us say I have the following class -

class X {
int y;
};

Lot of other classes start using X.

Now, I want to make X a template class so that I can write,

template<class T>
class X {
T y;
};

How to minimize the impact on the client?

One solution I've used (besides the obvious typedef) is inheritance:
template<class T>
class generic_X { /*** };

class X : public generic_X<int> { /* backwards-compatibility stuff */
};

In some cases, when the difference is too big, private inheritance
can be the better solution.

HTH,
Michiel Salters
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top