Suppose you have:
template<class T>
class A {
template<class T1>
void foo(const T1& t1) {}
//
// Lots of other definitions (all templated)
//
};
and you would like to specialize foo(const T1&)
but only for a specialized A<bool>
. Like this:
template<>
class A<bool> {
template<class T1>
void foo(const T1& t1) {
// Code for specialized A<boo>::foo
}
//
// Repeating the former definitions, how to avoid this ??
//
};
But to get this to work I have to duplicate all the code that is defined in the class template class A
and include it again in class A<bool>
.
I tried to define only the member specialization:
template<>
void A<bool>::template<class T1> foo(const T1&) {}
Neither does this work:
template <class T1> void A<bool>::foo(const T1&) {}
But the compiler doesn't like it. What's the way to deal with this code duplication?
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
Can there be more than one argument to templates? Yes, like normal parameters, we can pass more than one data type as arguments to templates.
Key differences between generics and C++ templates: Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime. The common language runtime specifically supports generics in MSIL.
Explicit (full) specializationAllows customizing the template code for a given set of template arguments.
Syntax? See this answer. Try:
template<>
template<typename T1>
void A<bool>::foo(const T1&){}
You certainly don't need to copy the whole class template.
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