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.
Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Templates Specialization is defined as a mechanism that allows any programmer to use types as parameters for a class or a function. A function/class defined using the template is called a generic function/class, and the ability to use and create generic functions/classes is one of the critical features of C++.
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>() { }
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>()
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With