Template Type Functions

M

Mike

I have a class temple which has to handle strings differently. Only a few
functions have to handle the string type differently. Is there anyway I can
do this without having two 'complete' classes, one generic and one for
strings only. I would just like to define the functions which are
different.

// Class Header example (there are other funcitons - this is just
// to show what I have done - and what I am trying to do.

tempate <class T>
class xList
{
public:
xList();
~xList();
T GetListVal();
void SetListVal( T );
private:
T *Ptr;
T Val;
};

tempate <>
class xList<std::string>
{
public:
xList();
~xList();
string GetListVal();
void SetListVal( string );
private:
string Val;
};

The only function that will be different is the 'string GetListVal()' - is
there anyway I can just define a special 'string' function for the
GetListVal() when the class is typed as string?

Thanks
Mike
 
V

Victor Bazarov

Mike said:
I have a class temple which has to handle strings differently. Only a few
functions have to handle the string type differently. Is there anyway I can
do this without having two 'complete' classes, one generic and one for
strings only. I would just like to define the functions which are
different.

// Class Header example (there are other funcitons - this is just
// to show what I have done - and what I am trying to do.

tempate <class T>
class xList
{
public:
xList();
~xList();
T GetListVal();
void SetListVal( T );
private:
T *Ptr;
T Val;
};

tempate <>
class xList<std::string>
{
public:
xList();
~xList();
string GetListVal();
void SetListVal( string );
private:
string Val;
};

The only function that will be different is the 'string GetListVal()' - is
there anyway I can just define a special 'string' function for the
GetListVal() when the class is typed as string?

You may provide an explicit specialisation of that function for 'string'
type instead of the whole class:

template<> string xList<string>::GetListVal() {
blah blah blah;
return somestring;
}

The rest of the class implementation will be picked by instantiating the
template members.

V
 
M

Mike

Victor Bazarov said:
You may provide an explicit specialisation of that function for 'string'
type instead of the whole class:

template<> string xList<string>::GetListVal() {
blah blah blah;
return somestring;
}

The rest of the class implementation will be picked by instantiating the
template members.

V

Thanks for response, that is exactly what I was looking for.

Mike
 

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
474,200
Messages
2,571,046
Members
47,646
Latest member
xayaci5906

Latest Threads

Top