Re: Metaprocessing problem
Christopher Dearlove wrote:
Suppose I have
template<int N> class D
{
// Can add anything needed here ...
};
and, for example
typedef D<U1> D1;
typedef D<U2> D2;
These may be assumed to be defined elsewhere, so while we know
D1 and D2 are of this form (or if they are not we don't care if the code
compiles or not - better if it doesn't) we don't know what U1 and U2
are.
Now I would like to be able, from D1 and D2 to find D<U1+U2>, in
an easy to move way, for example it might be
A<D1, D2>::Type
for a suitable template class A.
How about:
template <int N>
struct D
{
static const int value = N;
};
template < class T1, class T2>
struct Sum
{
static const int value = T1::value + T2::value;
};
typedef D<3> D3;
typedef D<10> D10;
// one way to perform the "addition"
typedef D< D3::value + D10::value> D13;
// or declare a specialization...
template <int N1, int N2>
struct Sum< D<N1>, D<N2> >
{
static const int value = N1 + N2;
typedef D<N1 + N2> type;
};
int main()
{
// and add D3 and D10 this way...
int i = Sum<D3, D10>::value;
std::cout << i << "\n";
// ...or like this
Sum<D3, D10>::type d13;
std::cout << d13.value << "\n";
}
Program Output:
13
13
Some older C++ compilers (VC6 included) do not support inline
initialization of static const members, such as D<N>::value above. For
those compilers, it is necessary to initialize the static const member
in a source file and just have the member be declared in the class
definition. For example:
template <int N>
struct D
{
static const int value;
};
template <int N> int D<N>::value = N;
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]