Re: Unresolved externals on static members in nested templates
Mikael Andersson wrote:
I'm using nested templates in an access-time optimisation storage class
and I'm trying to use static members to store commonly data which values
are calcualable at compile time. However, static members in nested
templates consitently result in unresolved external link errors when
compiling with Visual Studio 2005's compiler (I have not tried any other
compiler). Boiling down the problem to the bones leaves me with this
structure:
template<typename T>
struct Outer
{
static int outer_member;
template<int TT> struct Inner;
template<> struct Inner<1>
{
static int inner_member;
};
};
It's not legal to specialize an inner class template without
specializing each enclosing class template. And although VC may allow
it, it's not standard C++.
template<typename T> int Outer<T>::outer_member = 0;
This definition is OK.
template<typename T> template<int TT> int
Outer<T>::Inner<1>::inner_member = 0;
This definition is not. As noted above, the Inner class template cannot
be specialized without the Outer class template being specialized as
well.
One way of solving this problem would be to "reverse" the Inner and
Outer class templates. Moreover, since the concepts of "inner" and
"outer" when applied to templates more aptly refer to levels of
template instantiation rather layers of nested classes - it would make
sense to use an instantiation of one class template to instantiatate
the other.
So implementing these suggestions would produce a program like the
following:
// Outer class template
template<typename T>
struct Outer
{
static int outer_member;
};
// Outer::outer_member definition
template <class T> int Outer<T>::outer_member = 0;
// Inner class template
template <class T, int N> struct Inner;
// Inner class template partial specialization
template <class T>
struct Inner<Outer<T>, 1>
{
static int inner_member;
};
// Inner::inner_member definition (partial specialization)
template <class T>
int Inner<Outer<T>, 1>::inner_member = 0;
int main()
{
Outer<void> foo;
foo.outer_member = 1;
Inner<Outer<void>, 1>::inner_member = 1;
}
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]