Philipp Gebhard
Philipp Gebhard

Reputation: 301

Is it possible to specialize a template for templated types?

For my program i need to define a Solver class which can either solve a problem or nested problem.

template< typename ProblemT >
struct Solver {
    static void a() {
        ProblemT::func();
    }
};

template< typename < typename SubT> ProblemT >
struct Solver<ProblemT< SubT> > {
    static void a() {
        ProblemT::func();
        SubT::func();
    }
};

Usage:

Solver<Problem1> solver;
Solver<Problem2<Problem3> > nested_solver;

In the specialized version of Solver i need to know both ProblemT and SubT types in order to define the types correctly and call the correct functions.

Is there just a simple error or is it impossible to define such a class?

Upvotes: 1

Views: 148

Answers (2)

Paul Manta
Paul Manta

Reputation: 31577

You can do this using template template parameters:

template<template <typename> class ProblemT, typename SubT>
struct Solver<ProblemT<SubT>>
{
    ...
};

// And you use it like this
Solver<ProblemTemplate<SubProblem>> solver;

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477040

You can try something like this:

template <typename T>
struct Solver
{
    static void solve() { T::func(); }
};

template <template <typename> class Tmpl, typename U>
struct Solver<Tmpl<U>>
{
    static void solve() { Tmpl<U>::solve(); }
};

Obviously, you can decorate your primary Solver template with further member functions which you can access in the specialization, etc.

Upvotes: 3

Related Questions