Re: Defining member template specialization outside the class template declaration
Christian Larsen wrote:
Hi,
How do I define a member template specialization outside the class
template declaration?
In the example code below the getData<ONE> works just fine (defined
inside the class template), but the definition of getData<TWO> outside
the class template does not compile. I guess the syntax is wrong, but I
tried different things to no avail, and I couldn't find anything on the
net.
I'm compiling using MSVC8 (SP1).
template <class T>
class Foo
{
public:
enum Index { ONE = 1, TWO };
template <Index index>
T& getData();
template <>
T& getData<ONE>() { return data1; }
template <>
T& getData<TWO>();
private:
T data1;
T data2;
};
template <class T>
template <>
inline T& Foo<T>::getData<typename Foo<T>::TWO>()
{
return data2;
}
int main(int argc, char* argv[])
{
typedef Foo<int> IntFoo;
IntFoo f;
f.getData<IntFoo::ONE>() = 1;
f.getData<IntFoo::TWO>() = 2;
return 0;
}
<std>
14.7.3 Explicit specialization 14 Templates
17 A member or a member template may be nested within many enclosing
class templates. If the declaration of an explicit specialization for
such a member appears in namespace scope, the member declaration shall
be preceded by a template<> for each enclosing class template that is
explicitly specialized.
18 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. In such explicit specialization
declaration, the keyword template followed by a template-parameter-list
shall be provided instead of the template<> preceding the explicit
specialization declaration of the member. The types of the
template-parameters in the template-parameter-list shall be the same as
those specified in the primary template definition. [Example:
template<class T1> class A {
template<class T2> class B {
template<class T3> void mf1(T3);
void mf2();
};
};
template<> template<class X>
class A<int>::B { };
template<> template<> template<class T>
void A<int>::B<double>::mf1(T t)
{ }
template<class Y> template<>
void A<Y>::B<double>::mf2()
{ } // ill-formed; B<double> is specialized but
// its enclosing class template A is not
</std>
You can't specialize "getData" without specializing the the enclosing
class template "Foo";
So we can only have
template <>
template <class T>
....
but not
template <class T>
template <>
....
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]