Specialization of only one template parameter?

J

Joseph Turian

How can I specialize the value of only one template parameter?

Here's the fragment of code I'd like to get working:

typedef enum {START, PARENT, CHILD, END} locator_ty;
template <locator_ty L, bool Signed>
class foo {
string str();
...
};

template <bool Signed> string foo<START, Signed>::str() const { return
"start"; }
template <bool Signed> string foo<END, Signed>::str() const { return
"end"; }
template <bool Signed> string foo<PARENT, Signed>::str() const { return
"parent"; }
template <bool Signed> string foo<CHILD, Signed>::str() const { return
"child"; }


Except the last four lines aren't syntactically correct.
Can anyone tell me the correct syntax?
Thanks!

Joseph
 
V

Victor Bazarov

Joseph said:
How can I specialize the value of only one template parameter?

Here's the fragment of code I'd like to get working:

typedef enum {START, PARENT, CHILD, END} locator_ty;
template <locator_ty L, bool Signed>
class foo {
string str();
...
};

template <bool Signed> string foo<START, Signed>::str() const { return
"start"; }
template <bool Signed> string foo<END, Signed>::str() const { return
"end"; }
template <bool Signed> string foo<PARENT, Signed>::str() const { return
"parent"; }
template <bool Signed> string foo<CHILD, Signed>::str() const { return
"child"; }


Except the last four lines aren't syntactically correct.
Can anyone tell me the correct syntax?

There is none. What you're trying to do is to have a partial
specialisation of a function template. There is no such thing in C++.
You need to partially specialise the whole class. Example:

template<bool Signed>
class foo<END, Signed> {
string str() { return "end"; }
...
};

of course it may not be what you want because you need to re-implement all
the members there. You need to redesign. Why couldn't you, for example,
simply have 'str' member call another function, fully specialised, or that
has one argument:

string external_str(locator_ty L)
{
switch (L) {
case START: return "start";
case END: return "end";
}
}

template<locator_ty L> string ex_str(); // declaration

template<> string ex_str<START>() { return "start"; } // spec'tion
template<> string ex_str<END>() { return "end"; } // spec'tion


template<locator_ty L, bool Signed>
class foo {
string str() { return external_str(L); }
or
string str() { return ex_str<L>(); }
...
};
?

V
 

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,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top