Allan
Allan

Reputation: 4720

Template construction: compose templates from templates

Is a way to compose a template<int> from the template<int, int>

I have tried the following code, but it does not compile:

#include <iostream>
template<int N, int M>
struct A { enum E { n = N, m = M }; };

template<template<int> class C>
struct B : public C<8> { };

int main(int argc, const char *argv[])
{
    typedef B< A<4> > T;
    T b;

    std::cout << T::n << std::endl;
    std::cout << T::m << std::endl;
    return 0;
}

Error:

test3.cxx: In function ‘int main(int, const char**)’:
test3.cxx:10:23: error: wrong number of template arguments (1, should be 2)
test3.cxx:3:12: error: provided for ‘template<int N, int M> struct A’
test3.cxx:10:25: error: template argument 1 is invalid
test3.cxx:10:28: error: invalid type in declaration before ‘;’ token
test3.cxx:13:22: error: ‘T’ is not a class or namespace
test3.cxx:14:22: error: ‘T’ is not a class or namespace

Upvotes: 4

Views: 169

Answers (2)

Alan Stokes
Alan Stokes

Reputation: 18974

At least in C++03 a template template parameter must have exactly the number of arguments required.

One way to achieve this would be to create a new template with the right arity that delegates to the original template:

template<int M>
struct Hack : A<4, M> { };

...

typedef B<Hack> T;

Upvotes: 2

Mark B
Mark B

Reputation: 96281

The following code prints out 4 and 8, I hope I inferred your meaning properly. The number of parameters in your template-template didn't match the number of the template you passed in.

#include <iostream>
template<int N, int M>
struct A { enum E { n = N, m = M }; };

template<template<int, int> class C, int Num>
struct B : public C<Num, 8> { };

int main(int argc, const char *argv[])
{
    typedef B< A, 4 > T;
    T b;

    std::cout << T::n << std::endl;
    std::cout << T::m << std::endl;
    return 0;
}

Upvotes: 3

Related Questions