21

I need to specialize a function template in c++.

template<typename T>  
void doStuff<T>() {}

To

template<>
void doStuff<DefinedClass>();

and

template<>
void doStuff<DefinedClass2>();

I guess that is not the correct syntax (since it is not compiling). How should I do it?
Also, Since I will have not undefined template parameters in doStuff<DefinedClass>, would it be possible to declare the body in a .cpp?

Note: doStuff will use T wihtin its body to declare a variable.

Mario Corchero
  • 5,257
  • 5
  • 33
  • 59

3 Answers3

18

The primary template doesn't get a second pair of template arguments. Just this:

template <typename T> void doStuff() {}
//                        ^^^^^^^^^

Only the specializations have both a template <> at the front and a <...> after the name, e.g.:

template <> void doStuff<int>() { }
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Thanks, but still not working. If I write the specialization like: "template<> void doStuff();" I got: "invalid explicit specialization before '>' token" – Mario Corchero Feb 08 '13 at 09:59
  • If I put" template" I get "template-id `buildBom' in declaration of primary template" – Mario Corchero Feb 08 '13 at 10:00
  • 3
    No, it should be `template<> void doStuff();` for specialization and `template void doStuff();` for general case... – Synxis Feb 08 '13 at 10:01
  • @Synxis: Thanks! I added that example, and I removed the `...` from the first set, because you can't partially specialize functions anyway. Sometimes a less general answer is more helpful :-) – Kerrek SB Feb 08 '13 at 10:18
7

The correct syntax for the primary template is:

template <typename T>
void doStuff() {}

To define a specialisation, do this:

template <>
void doStuff<DefinedClass>() { /* function body here */ }
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
3

I guess that is not the correct syntax (since it is not compiling). How should I do it? doStuff will use T wihtin its body to declare a variable.

template<typename T>  
void doStuff() 
{
  T t = T();   // declare a T type variable

}

would it be possible to declare the body in a .cpp?

C++ only supports inclusive mode only, you can't compile separately then link later.

From comment, if you want to specialize for int type:

template<>
void doStuff<int>()
{
}
billz
  • 44,644
  • 9
  • 83
  • 100
  • ***inclusive mode***? What's that? Could you please explain that in more detail for me? – John Nov 23 '22 at 02:49