简体   繁体   中英

Template Specialization for a function without Parameters

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.

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, eg:

template <> void doStuff<int>() { }

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 */ }

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>()
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM