Hurricane Development
Hurricane Development

Reputation: 2464

C++ Overloading/Matching N nested templates

I am attempting to handle nested templates in c++ and am not even sure if this is possible. The point of this is to compile time type check n-th order derivatives. The following code is just an example of some more complicated stuff I am trying to do, but solving the following will extrapolate. Here is my base case:

struct XAxis {};
struct YAxis {};

template<typename T>
class Deriv {
    public:
        double a;
        Deriv(double in_a) : a(in_a) {};
}

template<>
class Deriv<XAxis> {
    public:
        double a;
        Deriv(double in_a) : a(in_a) {};
        double x() {
            return a;
        }
}

template<>
class Deriv<YAxis> {
    public:
        double a;
        Deriv(double in_a) : a(in_a) {};
        double y() {
            return a;
        }
}

The following then works:

Deriv<XAxis> xvel{1.0};
std::cout << xvel.x() << std::endl;

I then want to be able to do the following, but I'm not sure how to implement it:

Deriv<Deriv<YAxis>> yacc{1.0};
std::cout << yacc.y() << std::endl;

How do I accomplish this?

Upvotes: 0

Views: 40

Answers (1)

It appears to me that a partial specialization should do what your simplified example is after

template<typename T>
class Deriv<Deriv<T>> : public Deriv<T> {
    public:
        Deriv(double in_a) : Deriv<T>(in_a) {};
};

That should handle arbitrary nested Deriv specializations. Adding the above is enough to make your test case compile, which I assumed is the stated goal.

Upvotes: 3

Related Questions