Re: Forcing instantiation of a static member of a template
On 24 Okt., 20:24, Jiri Palecek <jpale...@web.de> wrote:
template <class T>
class A
{
public:
struct Reg { Reg(); };
static const Reg reg;
A();
};
template <class T>
const typename A<T>::Reg A<T>::reg;
template <class T>
A<T>::A() { ® }
However, that's really ugly, and I'd like not to rely on hacks like that.
What happens here that you consider this to be a "hack"?
The first problem I see is the lack of a more exact
description for which scenarios you want the registration
to occur? Just in those cases, when an object A<T>
is created during the runtime of the program?
Which-ever definition you will give, there will be the
problem that the pure usage of the type name will
not lead to such registration, e.g. by doing this:
typedef A<int> MyA;
void foo(A<std::string>&);
But if I use an explicit instantiation:
... class A same as above ...
template <class T>
const typename A<T>::Reg A<T>::reg;
template <class T>
A<T>::A() { template static const A<T>::Reg A<T>::reg; }
I get errors from the compiler. Intel says "explicit instantiation is not
allowed here", gcc says even more cryptic syntax error "; expected
before 'template'".
The compiler is right, this is definitively *not* an
explicit instantiation. Actually I'm not sure that I
understand your indent: Why do you define a non-local
A<T>::reg *and* try to define a local static variable
of type A<T>::Reg? If you properly want to do the last
thing, you simply write this:
template <class T>
A<T>::A() { static const Reg reg; }
Of course, this can lead to other problems, if A has more
than one c'tor - each local static inside those c'tors
belongs to another Reg object.
However, the standard says that
A member function, member class or static data member of a class template
can be explicitly instantiated from the member definition associated with
its class template.
and that the definition of the instantiated member shall be in scope at the
point of the explicit instantiation, which (I think) is true in this case.
So am I missing something or do all the compiler writers get it wrong?
The compiler writers are correct, and the standard hastens to add the
following in [temp.explicit]/5:
"[..] An explicit instantiation for a member of a class template is
placed
in the namespace where the enclosing class template is defined.[..]"
Your attempt to provide an explicit instantiation in a function scope
is not supported - and what do you want to you realize with this?
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]