Re: How to inject templated types in a namespace ?
X Ryl wrote:
Hi,
I have a problem I cannot find a solution to, so I'm wondering if a
technic already exists for it.
Here it is:
namespace TypeRegistry
{
struct TypeID
{
// An common interface for type ID manipulation
};
template <typename T>
struct TypeIDImpl : public TypeID
{
// Some const members
// And no default constructor so this type doesn't compile
as is
} ;
// This function compiles if and only if TypeIDImpl has been
specialized
template <typename T>
static TypeID * getTypeID(T * t) { static TypeIDImpl<T> ti;
return
&ti; }
}
namespace Other
{
struct Base {};
template <typename T>
struct Some : public Base
{
// See below
};
}
The idea is simple. The TypeRegistry namespace holds all functions for
manipulating type information. Anytime you want some information about
a type, you call getTypeID(YourType) and get a unique identifier (just
like typeinfo).
I've specialized TypeIDImpl for a any new type.
Now I would like to either :
- find a way to inject a specialized getTypeID for any Some<T> in
the TypeRegistry namespace AUTOMATICALLY (I don't want to write an
overload for each "T" I would be using)
A program specializes a class template precisely to prevent the
compiler from automatically generating code for a particular class from
the template. So it makes little sense for a program to have the
compiler generate code for specializations when the sole purpose of a
specialization is to prevent the compiler from automatically generating
code. Why wouldn't such a program simply have the template generate the
desired code in the first place, rather than follow such a convoluted
approach of alternately suppressing and enabling the
automatically-generated code?
And indeed what is the rationale for requiring that TypeIDImpl be
specialized for every type? And if the program really has to specialize
each type, what then is the benefit of using templates? The program
would have to provide just as much code without templates, so why
bother with a class template in the first place?
- Automatically create a TypeIDImpl<Some<T> > given T
The compiler will automatically generate a template class as long as it
is used somewhere. So why generate TypeIDImpl<Some<T> > unless it is
used? And if it used, then the program does not need to worry about
generating the template class itself.
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]