Mike N.
Mike N.

Reputation: 1752

C++: Declare type as variant of another templated type

In the following code I define an AnotherClass template to take type two parameters. Each of those parameters is a type created by another template. The only difference between the two type parameters is the value of an int parameter passed to those types' templates. The comments show what I really want to do.

#include <iostream>
using namespace std;

template <int size> 
class MyClass {
private:
    int sz;
public:
    MyClass() {
        this->sz = size;
    }
    void tellSize() {
        cout << this->sz;
    }
    int length() {
        return this->sz;
    }
};

// template <typename T1>
template <typename T1, typename T2>
class AnotherClass {
private:
    T1 myC;
    T2 myCp1;
    //templateof(T1)<parameterof(T1)+1> myCp1;
public:
};

int main() {
    //AnotherClass<MyClass<10> > myC;
    AnotherClass<MyClass<10>, MyClass<11> > myC;
    return 0;
}

What I really want to do is statically declare myCp1's type as "use myC's template with myC's parameter incremented by 1" without having to pass both types to the AnotherClass template...

Is there a way to achieve this?

Upvotes: 3

Views: 104

Answers (1)

Pradhan
Pradhan

Reputation: 16777

You can provide a partial specialization of AnotherClass which does pattern-matching to separate out the template class and template parameter.

template <typename T>
class AnotherClass;

template <template <int> class SomeTemplate, int size>
class AnotherClass<SomeTemplate<size> >
{
  SomeTemplate<size> myC;
  SomeTemplate<size+1> myCp1;
};

Upvotes: 3

Related Questions