specialize a template function that contains a template parameter

S

sebastian

Hi,
I'd like to specialize a template function that contains a template
parameter. In Example i have the following function declared:

....

template < int i > static stupid_object& doSomething( int i,
const another_stupid_object& __aso);

....

and now i would like to specialize this function for i equals 6.
How can i realize this ?:

....
template<> stupid_object& doSomething( ???? ) {
....
}
....

In the broader sens what happens if the template-argument is not of a
simple type like "int" but an own declared object (i.E. "own_object").
Which operators do i have to overwrite ? Is there any documentation about
this ?
Unfortunately Stroustrup doesn't write anything about this case. Is
it generally realizable/implementable ???

Thanx in advance
cheers
sebastian
 
G

Greg

sebastian said:
Hi,
I'd like to specialize a template function that contains a template
parameter. In Example i have the following function declared:

...

template < int i > static stupid_object& doSomething( int i,
const another_stupid_object& __aso);

...

and now i would like to specialize this function for i equals 6.
How can i realize this ?:

...
template<> stupid_object& doSomething( ???? ) {
...
}
...

In the broader sens what happens if the template-argument is not of a
simple type like "int" but an own declared object (i.E. "own_object").
Which operators do i have to overwrite ? Is there any documentation about
this ?
Unfortunately Stroustrup doesn't write anything about this case. Is
it generally realizable/implementable ???

Thanx in advance
cheers
sebastian

It is not possible for the compiler to deduce a non-type template
parameter for a function template. To do so, the compiler would have to
know which calls to that function passed the value 6, and also be sure
that the value passed was always 6. Since it can do neither, the
compiler requires that every call to doSomething specifies the non-type
parameter:

doSomething<6>( i, a);

Of course, this syntax is no better than simply writing a function
called doSomething6. And for that reason function templates are rarely
declared with non-type parameters. They just are not very useful.

But to answer the question, a function template with an int
parameterized type can be specialized for the value 6 in this way:

template <>
int DoSomething<6>(int i, someType s)
{
...

Greg
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top