Is it possible to have a specialized template class which is a member of a template class(that is not specialized per se)?
With a non-template parent class this works:
class owner
{
template<int num>
struct s
{
int ret() { return num; }
};
};
template<>
struct owner::s<0>
{
int ret() { return 0; }
};
But when making owner
a template class it does not:
template<typename some>
class owner
{
template<int num>
struct s
{
int ret() { return num; }
};
};
template<typename some>
struct owner<some>::s<0>
{
int ret() { return 0; }
};
Searching shows that this is not possible(?) for functions, but how about classes/structs? Specializing a templated member of a template class
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.
It's not the method that is templated, it's the class. You can have a templated method in a non-templated class, a non-templated method in a templated class (your case) and a templated method in a templated class, and of course a non-templated method in a non-templated class. Save this answer.
Member functions of class templates (C++ only)You may define a template member function outside of its class template definition. The overloaded addition operator has been defined outside of class X . The statement a + 'z' is equivalent to a. operator+('z') .
Inheriting from a template classIt is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.
No, that is not possible. A member class template can only be specialised if all of its enclosing class templates are also specialised. Quoting C++2x (N4713) [temp.expl.spec] 17.8.3/17:
In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.
(Emphasis mine)
In some cases, you could get around this by making the nested name s
an alias to a namespace-scope helper which can be partially specialised. Something like this:
template <class some, int num>
struct s_helper
{
int ret() { return num; }
};
template<typename some>
class owner
{
template<int num>
using s = s_helper<some, num>;
};
template<typename some>
struct s_helper<some, 0>
{
int ret() { return 0; }
};
To reduce the exposure of s_helper
, it can of course be hidden in a suitably named internal namespace (such as detail
).
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